package com.iris.live.services.services.impl;

import com.google.gson.JsonObject;
import com.iris.live.services.common.*;
import com.iris.live.services.common.reconsitution.MessageContext;
import com.iris.live.services.common.reconsitution.MessageType;
import com.iris.live.services.data.models.*;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.RequestBase;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.report.ExcelReportContext;
import com.iris.live.services.report.IExcelReportService;
import com.iris.live.services.report.IExcelReportSource;
import com.iris.live.services.services.CRMService;
import com.iris.live.services.vo.crm.ItemsVo;
import com.iris.live.services.vo.crm.ReportVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

import static com.iris.live.services.common.LshMsgUtils.getLshMsg;

/**
 * Created by lusong on 2016/11/7.
 */
@Service
@Transactional
public class CRMServiceImpl implements CRMService {
    private static final String[] surveyResultType = {"完成问卷","待跟进","无效电话","拒绝回访","重新分配","投诉","激活并分配","推荐名单推送"};
    private static Logger logger = LoggerFactory.getLogger(CRMServiceImpl.class);
    @Autowired
    private CrmTopicRepository crmTopicRepository;

    @Autowired
    private CrmAnswerRepository crmAnswerRepository;

    @Autowired
    private CrmTopicSQLRepository crmTopicSQLRepository;

    @Autowired
    private CrmTopicLogRepository crmTopicLogRepository;

    @Autowired
    private 销售项目设置Repository repository销售项目设置;

    @Autowired
    private 顾客记录汇总Repository repository顾客记录汇总;

    @Autowired
    private 顾客记录汇总SQLRepository repository顾客记录汇总SQL;

    @Autowired
    private 用户Repository repository用户;

    @Autowired
    private Lsh消息Repository lsh消息Repository;

    @Autowired
    private Lsh导入名单Repository lsh导入名单Repository;

    @Autowired
    private CrmExploreRepository crmExploreRepository;

    @Autowired
    private CrmFlowRepository crmFlowRepository;

    @Autowired
    private CrmRearchIntentRepository crmRearchIntentRepository;

    @Autowired
    private CrmHistoryRepository crmHistoryRepository;

    @Autowired
    private CrmComplaintRepository crmComplaintRepository;

    @Autowired
    private CrmHistorySQLRepository crmHistorySQLRepository;

    @Autowired
    private CRMRepository crmRepository;

    @Autowired
    private CrmHistoryLogRepository crmHistoryLogRepository;

    @Autowired
    private SalesClueSetRepository salesClueSetRepository;

    @Autowired
    private IExcelReportService excelReportService;

    @Autowired
    private Lsh经销商表Repository lsh经销商表Repository;

    @Resource(name = "ExportDealerSurveyResultSource")
    private IExcelReportSource ExportDealerSurveyResultSource;

    @Resource(name = "ExportGroupSurveyResultSource")
    private IExcelReportSource ExportGroupSurveyResultSource;

    @Resource(name = "ExportLiveClueSource")
    private IExcelReportSource ExportLiveClueSource;

    @Resource(name = "ExportCRMSurveySource")
    private IExcelReportSource ExportCRMSurveySource;

    /**
     * 通过 stage 阶段 获取当前使用的题库及答案
     *
     * @param stage
     * @param permit
     * @return
     */
    @Override
    @Transactional
    public ResultData topicCurrentQuery(String permit, String stage) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List list = crmTopicSQLRepository.topicCurrentQuery(permit, stage);
            if (list != null && !list.isEmpty()) {
                Map getVersionMap = (Map) list.get(0);
                resultData.setMessage(getVersionMap.get("version").toString());
                for (Object o : list) {
                    Map map = (Map) o;
                    List<CrmAnswerModel> listAnswer = crmAnswerRepository.queryAnswerByTopicId(Integer.parseInt(map.get("id").toString()));
                    if (listAnswer != null && !listAnswer.isEmpty()) {
                        for (int i = 0; i < listAnswer.size(); i++) {
                            map.put("select" + (i + 1), listAnswer.get(i).getResponse());
                            map.put("forwardEnding" + (i + 1), listAnswer.get(i).getForwardEnding());
                        }
                    }
                }
            } else {
                resultData.setMessage("暂未导入相关题库");
            }
            resultData.setResult("true");
            resultData.setPageData(new PageData(list, 0));
        } catch (Exception e) {
            logger.error("查询题库及答案异常", e);
        }
        return resultData;
    }

    /**
     * 题库导入，保存到数据库
     *
     * @param permit
     * @param stage
     * @param list
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData topicLeadingIn(String permit, String username, String stage, List<GetCurrentTopic> list) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateString = sdf.format(new Date());
        int versionNum = crmTopicSQLRepository.findCurrentVersionNum(stage, "%" + dateString + "%");
        String version = null;
        //生成题库版本号
        if (GetConfigureInfoUtils.getConfigureInfo("file_group").equals(permit)) {
            version = "DCH-";
        } else {
            version = permit + "-";
        }
        if ("01".equals(stage)) {
            version = version + "SCLD-";
        } else if ("02".equals(stage)) {
            version = version + "XMDY-";
        } else if ("03".equals(stage)) {
            version = version + "ZBDY-";
        } else if ("04".equals(stage)) {
            version = version + "NPSDY-";
        } else {
            resultData.setResult("false");
            resultData.setMessage("stage不在规定值域内");
            return resultData;
        }
        if (versionNum < 9) {
            version = version + dateString + "00" + (versionNum + 1);
        } else if (versionNum < 99) {
            version = version + dateString + "0" + (versionNum + 1);
        } else {
            version = version + dateString + (versionNum + 1);
        }
        if (list == null || list.size() < 1) {
            resultData.setMessage("题库导入有误");
            return resultData;
        } else {
            if (!GetConfigureInfoUtils.getConfigureInfo("file_group").equals(permit)) {
                String groupVersion = crmTopicRepository.queryMaxVersionByPermitAndSatge(GetConfigureInfoUtils.getConfigureInfo("file_group"), stage, "%DCH%");
                if (!StringUtils.isNullOrBlank(groupVersion)) {
                    List<CrmTopicModel> crmTopicModels = crmTopicRepository.findTopicByVersion(GetConfigureInfoUtils.getConfigureInfo("file_group"), groupVersion);
                    if (crmTopicModels != null && !crmTopicModels.isEmpty()) {
                        if (crmTopicModels.size() + list.size() > 10) {
                            resultData.setMessage("集团和经销商调研问卷不能超过10题");
                            return resultData;
                        }
                    }
                } else {
                    resultData.setMessage("请先导入集团调研问卷");
                    return resultData;
                }
            } else {
                if (list.size() > 10) {
                    resultData.setMessage("集团调研问卷不能超过10题");
                    return resultData;
                }
            }
            //导入题库及答案信息
            for (GetCurrentTopic getCurrentTopic : list) {
                //保存题目
                String type = null;
                if ("单选".equals(getCurrentTopic.type)) {
                    type = "01";
                } else if ("多选".equals(getCurrentTopic.type)) {
                    type = "02";
                } else if ("开放".equals(getCurrentTopic.type)) {
                    type = "03";
                } else {
                    resultData.setResult("false");
                    resultData.setMessage("type参数信息有误");
                    return resultData;
                }
                CrmTopicModel crmtopicModel = new CrmTopicModel();
                crmtopicModel.setPermit(permit);
                crmtopicModel.setStage(stage);
                crmtopicModel.setVersion(version);
                crmtopicModel.setType(type);
                crmtopicModel.setNumber(getCurrentTopic.number);
                crmtopicModel.setLead(getCurrentTopic.lead);
                crmtopicModel.setStem(getCurrentTopic.stem);
                crmtopicModel.setForward(getCurrentTopic.forward);
                crmtopicModel.setRemark(getCurrentTopic.remark);
                crmtopicModel = crmTopicRepository.save(crmtopicModel);

                if (crmtopicModel == null) {
                    resultData.setMessage("保存题目失败");
                    return resultData;
                }

                //保存答案
                if (getCurrentTopic.select1 != null && !"".equals(getCurrentTopic.select1)) {
                    saveCrmAnswer(crmtopicModel.getId(), getCurrentTopic.select1, getCurrentTopic.forwardEnding1);
                }
                if (getCurrentTopic.select2 != null && !"".equals(getCurrentTopic.select2)) {
                    saveCrmAnswer(crmtopicModel.getId(), getCurrentTopic.select2, getCurrentTopic.forwardEnding2);
                }
                if (getCurrentTopic.select3 != null && !"".equals(getCurrentTopic.select3)) {
                    saveCrmAnswer(crmtopicModel.getId(), getCurrentTopic.select3, getCurrentTopic.forwardEnding3);
                }
                if (getCurrentTopic.select4 != null && !"".equals(getCurrentTopic.select4)) {
                    saveCrmAnswer(crmtopicModel.getId(), getCurrentTopic.select4, getCurrentTopic.forwardEnding4);
                }
                if (getCurrentTopic.select5 != null && !"".equals(getCurrentTopic.select5)) {
                    saveCrmAnswer(crmtopicModel.getId(), getCurrentTopic.select5, getCurrentTopic.forwardEnding5);
                }
                if (getCurrentTopic.select6 != null && !"".equals(getCurrentTopic.select6)) {
                    saveCrmAnswer(crmtopicModel.getId(), getCurrentTopic.select6, getCurrentTopic.forwardEnding6);
                }
                if (getCurrentTopic.select7 != null && !"".equals(getCurrentTopic.select7)) {
                    saveCrmAnswer(crmtopicModel.getId(), getCurrentTopic.select7, getCurrentTopic.forwardEnding7);
                }
                if (getCurrentTopic.select8 != null && !"".equals(getCurrentTopic.select8)) {
                    saveCrmAnswer(crmtopicModel.getId(), getCurrentTopic.select8, getCurrentTopic.forwardEnding8);
                }
                if (getCurrentTopic.select9 != null && !"".equals(getCurrentTopic.select9)) {
                    saveCrmAnswer(crmtopicModel.getId(), getCurrentTopic.select9, getCurrentTopic.forwardEnding9);
                }
                if (getCurrentTopic.select10 != null && !"".equals(getCurrentTopic.select10)) {
                    saveCrmAnswer(crmtopicModel.getId(), getCurrentTopic.select10, getCurrentTopic.forwardEnding10);
                }
            }
        }
        //保存日志
        CrmTopicLogModel crmTopicLogModel = new CrmTopicLogModel();
        crmTopicLogModel.setPermit(permit);
        crmTopicLogModel.setVersion(version);
        crmTopicLogModel.setUpdateSendInfoDate(new java.sql.Date(new Date().getTime()));
        crmTopicLogModel.setUpdateTime(new Timestamp(new Date().getTime()));
        crmTopicLogModel.setUpdateAccount(username);
        crmTopicLogRepository.save(crmTopicLogModel);
        resultData.setResult("true");
        resultData.setMessage(version);
        return resultData;
    }

    //保存答案
    private CrmAnswerModel saveCrmAnswer(int id, String answer, String forwardEnding) {
        CrmAnswerModel crmAnswerModel = new CrmAnswerModel();
        crmAnswerModel.setStemId(id);
        crmAnswerModel.setResponse(answer);
        crmAnswerModel.setForwardEnding(forwardEnding);
        return crmAnswerRepository.save(crmAnswerModel);
    }

    /**
     * 查询sc战败，但CRM战败确认待分配的顾客信息，查询列表
     *
     * @param permit
     * @param pageIndex
     * @return
     */
    @Override
    @Transactional
    public PageData scFailNewAssigned(String permit, int pageIndex, int pageSize, String search) {
        return repository顾客记录汇总SQL.scFailNewAssigned(permit, pageIndex, pageSize, search);
    }

    public List<?> getAssignedSC(String permit, String currentSC) {
        return repository顾客记录汇总SQL.getAssignedSC(permit, currentSC, null);
    }

    /**
     * 给顾客分配新的sc
     * @param permit
     * @param username
     * @param custid
     * @param sccode
     * @return
     */
    @Override
    @Transactional
    public Map updateCusAboutSC(String permit, String username, String custid, String sccode) {
        Map map = new HashMap();
        用户Model model用户 = repository用户.findBy许可And用户名(permit, sccode);
        顾客记录汇总Model model顾客记录汇总 = repository顾客记录汇总.findCusByCustomerID(Integer.parseInt(custid));
        //校验 分配的销售顾问 是否存在
        if (model用户 == null) {
            map.put("result", "false");
            map.put("message", "未找到该销售顾问");
            return map;
        }
        //校验 分配的 顾客 是否存在
        if (model顾客记录汇总 == null) {
            map.put("result", "false");
            map.put("message", "当前顾客详情不存在");
            return map;
        }

        销售项目设置ModelPK modelPK = new 销售项目设置ModelPK();
        modelPK.set许可(permit);
        modelPK.set设置项目("MGT_REDISTRIBUTION");
        销售项目设置Model model = repository销售项目设置.findOne(modelPK);
        int superLimitNum = 0;

        //校验 销售顾问高于未订单线索上限,LiVE i-Mgt是否无法重新分配线索给该销售顾问
        if (model != null && "是".equals(model.get值())) {
            int clueNum = 0;
            销售项目设置ModelPK modelPK1 = new 销售项目设置ModelPK();
            modelPK1.set许可(permit);
            modelPK1.set设置项目("线索总数上限");
            销售项目设置Model model1 = repository销售项目设置.findOne(modelPK1);
            if (model1 == null || StringUtils.isNullOrBlank(model1.get值())) {
                superLimitNum = 120;
            } else {
                superLimitNum = Integer.parseInt(model1.get值());
            }
            List<?> list = salesClueSetRepository.querySalesClueNum(permit, sccode);
            if (list != null && list.size() > 0) {
                Map clueMap = (Map) list.get(0);
                if (!StringUtils.isNullOrBlank(clueMap.get("counts"))) {
                    clueNum = Integer.parseInt(clueMap.get("counts").toString());
                    if (clueNum >= superLimitNum) {
                        map.put("result", "false");
                        map.put("message", "该销售顾问线索已达到上限");
                        return map;
                    }
                } else {
                    map.put("result", "false");
                    map.put("message", "获取销售顾问线索数有误!");
                    return map;
                }
            } else {
                map.put("result", "false");
                map.put("message", "获取销售顾问线索数有误!");
                return map;
            }
        } else {
            logger.info("未设置 高于未订单线索上限,LiVE i-Mgt无法重新分配线索给该销售顾问,高于线索上限的销售顾问也可分配");
        }

        model顾客记录汇总.set所属销售顾问(sccode);
        model顾客记录汇总.setCrm战败确认(2);
        model顾客记录汇总.set更新时间(DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date()));
        顾客记录汇总Model 顾客记录汇总ModelSave = repository顾客记录汇总.save(model顾客记录汇总);
        List<String> listString = new ArrayList<String>();
        listString.add(sccode);
        String msgContent = MessageContext.setNewScForCustomer(顾客记录汇总ModelSave.get顾客姓名(), 顾客记录汇总ModelSave.get电话号码());
        //系统消息提示
        Lsh消息Model message = LshMsgUtils.getLshMsg(permit, username, 顾客记录汇总ModelSave.get许可(), 顾客记录汇总ModelSave.get所属销售顾问(),
                "线索", msgContent, username, 顾客记录汇总ModelSave.get电话号码());
        //手机消息推送
        JPush.SendPushITaskForAndroidAndIos(msgContent, msgContent,
                JsonObjectUtils.getJsonObject(null, null, null, 顾客记录汇总ModelSave.get电话号码(),
                        顾客记录汇总ModelSave.get顾客编号() + "", sccode), listString);

        map.put("result", "true");
        return map;
    }

//    /**
//     * CRM确认战败或激活
//     * @param permit
//     * @param username
//     * @param getClueOperation
//     * @return
//     */
//    @Override
//    @Transactional
//    public ResultData updateCRMConfirmFailOrActivation(String permit, String username, GetClueOperation getClueOperation) {
//        ResultData resultData = new ResultData("false", null, null);
//        try {
//            CrmHistoryModel crmHistoryModel = crmHistoryRepository.findOne(Integer.parseInt(getClueOperation.historyId));
//            if (crmHistoryModel == null) {
//                resultData.setMessage("未找到相关调研记录");
//                return resultData;
//            }
//            顾客记录汇总Model model顾客记录汇总 = repository顾客记录汇总.findCusByCustomerID(crmHistoryModel.getCustId());
//            if (model顾客记录汇总 == null) {
//                resultData.setMessage("未找到相关顾客信息");
//                return resultData;
//            }
//            用户Model model = repository用户.findByCode(model顾客记录汇总.get所属销售顾问());
//            if (model == null) {
//                resultData.setMessage("未找到相关销售顾问信息");
//                return resultData;
//            }
//            if (getClueOperation != null) {
//                if ("2".equals(getClueOperation.crmFailConfirm)) {
//                    boolean flag = updateClueInfo(permit, username, getClueOperation, crmHistoryModel, model顾客记录汇总, model);
//                    if (flag) {
//                        resultData.setResult("true");
//                    } else {
//                        resultData.setMessage("修改线索信息失败");
//                    }
//                } else if ("0".equals(getClueOperation.crmFailConfirm)) {
//                    if ("04".equals(crmHistoryModel.getStage())) {
//                        resultData.setMessage("NPS调研不支持线索战败");
//                    } else {
//                        boolean flag = clueFail(permit, username, getClueOperation, crmHistoryModel, model顾客记录汇总, model);
//                        if (flag) {
//                            resultData.setResult("true");
//                        } else {
//                            resultData.setMessage("线索战败失败");
//                        }
//                    }
//                } else if ("1".equals(getClueOperation.crmFailConfirm)) {
//                    boolean flag = clueReallocation(permit, username, getClueOperation, crmHistoryModel, model顾客记录汇总, model);
//                    if (flag) {
//                        resultData.setResult("true");
//                    } else {
//                        resultData.setMessage("线索重新分配失败");
//                    }
//                }
//            }
//        } catch (Exception e) {
//            resultData.setMessage("程序异常");
//            logger.error("CRM确认战败或激活异常", e);
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//        }
//        return resultData;
//    }

//    //修改线索信息
//    private boolean updateClueInfo(String permit, String username, GetClueOperation getClueOperation, CrmHistoryModel crmHistoryModel, 顾客记录汇总Model model顾客记录汇总, 用户Model model) {
//        boolean flag = false;
//        try {
//            //CRM 将该 线索战败 即 0
//            model顾客记录汇总.set顾客状态("战败");
//            model顾客记录汇总.setCrm战败确认(0);
//            model顾客记录汇总.set更新账号(username);
//            model顾客记录汇总.set更新时间(new Timestamp(new Date().getTime()));
//            //调研状态 改为 接触失败 即 03
//            crmHistoryModel.setResearchState("03");
//            //调研记录状态 改为 1 即 已调研
//            crmHistoryModel.setHistoryState("1");
//            //发送信息给 销售顾问
//            Lsh消息Model message = LshMsgUtils.getLshMsg(permit, username, model.get许可(), model.get用户名(),
//                    "线索", getClueOperation.msgContent, username, model顾客记录汇总.get电话号码());
//
//            List<String> list = new ArrayList();
//            list.add(model.get用户名());
//            JsonObject json = JsonObjectUtils.getJsonObject("线索", null, null, model顾客记录汇总.get电话号码(), model顾客记录汇总.get顾客编号() + "", model顾客记录汇总.get所属销售顾问());
//            JPush.SendPushITaskForAndroidAndIos(getClueOperation.msgContent, getClueOperation.msgContent, json, list);
//            flag = true;
//        } catch (Exception e) {
//            logger.error("修改线索信息异常", e);
//            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
//        }
//        return flag;
//    }
//
//    //线索战败
//    private boolean clueFail(String permit, String username, GetClueOperation getClueOperation, CrmHistoryModel crmHistoryModel, 顾客记录汇总Model model顾客记录汇总, 用户Model model) {
//        boolean flag = false;
//        try {
//            //CRM 将该 线索战败 即 0，新车销售状态 改为 新车战败 即 8
//            model顾客记录汇总.set顾客状态("战败");
//            model顾客记录汇总.setCrm战败确认(0);
//            model顾客记录汇总.set新车销售状态(8);
//            model顾客记录汇总.set更新账号(username);
//            model顾客记录汇总.set更新时间(new Timestamp(new Date().getTime()));
//            //调研记录状态 改为 1 即 已调研
//            crmHistoryModel.setHistoryState("1");
//            //发送战败消息
//            Lsh消息Model message = LshMsgUtils.getLshMsg(permit, username, model.get许可(), model.get用户名(),
//                    "线索", getClueOperation.msgContent, username, model顾客记录汇总.get电话号码());
//
//            List<String> list = new ArrayList();
//            list.add(model.get用户名());
//            JsonObject json = JsonObjectUtils.getJsonObject("线索", null, null, model顾客记录汇总.get电话号码(), model顾客记录汇总.get顾客编号() + "", model顾客记录汇总.get所属销售顾问());
//            JPush.SendPushITaskForAndroidAndIos(getClueOperation.msgContent, getClueOperation.msgContent, json, list);
//            flag = true;
//        } catch (Exception e) {
//            logger.error("线索战败异常", e);
//            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
//        }
//        return flag;
//    }
//
//    //线索重新分配
//    private boolean clueReallocation(String permit, String username, GetClueOperation getClueOperation, CrmHistoryModel crmHistoryModel, 顾客记录汇总Model model顾客记录汇总, 用户Model model) {
//        boolean flag = false;
//        try {
//            //调研记录状态 改为 1 即 已调研
//            crmHistoryModel.setHistoryState("1");
//
//            model顾客记录汇总.set更新时间(new Timestamp(new Date().getTime()));
//            model顾客记录汇总.set更新账号(username);
//            //调研--激活并重新分配
//            //首次离店调研,休眠调研： Crm战败确认 = 1 （战败激活,待分配）,顾客状态 = 本月,将该线索推送给销售经理,并发送信息给销售经理
//            //战败调研：校验该线索所属销售顾问的线索数是否达到上限,
//            // 否：将该线索推给该销售顾问,顾客状态改为本月,crm战败确认改为2(战败激活,已分配)
//            // 是：将该线索推送给CDO,Crm战败确认 = 1 （战败激活,待分配）,顾客状态不做修改
//            if (!"03".equals(crmHistoryModel.getStage())) {
//                model顾客记录汇总.setCrm战败确认(1);
//                model顾客记录汇总.set顾客状态("本月");
//
//                //查询该许可下所有的销售经理
//                List<用户Model> list = repository用户.findAllManager(model顾客记录汇总.get许可());
//                List listUsername = new ArrayList();
//                if (list != null && !list.isEmpty()) {
//                    for (用户Model model用户 : list) {
//                        //给 销售经理 发送信息
//                        Lsh消息Model message = LshMsgUtils.getLshMsg(permit, username, model用户.get许可(), model用户.get用户名(),
//                                "线索", getClueOperation.msgContent, username, model顾客记录汇总.get电话号码());
//                        //编辑 极光推送 发送信息的 接收人
//                        listUsername.add(model用户.get用户名());
//                    }
//                    JsonObject json = JsonObjectUtils.getJsonObject("线索", null, null, model顾客记录汇总.get电话号码(), model顾客记录汇总.get顾客编号() + "", model顾客记录汇总.get所属销售顾问());
//                    JPush.SendPushITaskForAndroidAndIos(getClueOperation.msgContent, getClueOperation.msgContent, json, listUsername);
//                }
//            } else {
//                List list = repository顾客记录汇总SQL.getAssignedSC(permit, "", model顾客记录汇总.get所属销售顾问());
//                if (list != null && !list.isEmpty()) {
//                    model顾客记录汇总.setCrm战败确认(2);
//                    model顾客记录汇总.set顾客状态("本月");
//                } else {
//                    model顾客记录汇总.setCrm战败确认(1);
//                }
//            }
//            flag = true;
//        } catch (Exception e) {
//            logger.error("线索重新分配异常", e);
//            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
//        }
//        return flag;
//    }

    @Transactional
    public boolean saveClueAndResign(SaveClueAndResignReq req, String license, String user) {
        try {
            //接收人
            List list = new ArrayList();
            java.sql.Date dt = java.sql.Date.valueOf(LocalDate.now());
            Timestamp ts = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date());
            顾客记录汇总Model old顾客 = repository顾客记录汇总.findOne(Integer.valueOf(req.oldCusId));

            Lsh导入名单Model l = null;
            //只有推荐,才保存导入名单
            if ("1".equals(req.isClue)) {
                //1、判断是否是线索
                //有推荐
                //判断推荐的客户是否是有效客户：即三个月内是否有进店记录
                //2.判断此名单是否为有效线索,再导入lsh导入名单表
                Lsh导入名单Model entity = new Lsh导入名单Model();
                Calendar c = Calendar.getInstance();
                c.add(Calendar.MONTH, -2);
                Date endDate = DateFormatUtils.getFormatDate("yyyy-MM-dd", new Date());
                Date startDate = DateFormatUtils.getFormatDate("yyyy-MM-01", c.getTime());
                List<Lsh导入名单Model> lsh导入名单list = lsh导入名单Repository.isAvailableClue(req.newCusPhone, license, startDate, endDate);
                if (lsh导入名单list.size() > 0) {
                    //查出数据，说明此名单不是有效线索
                    entity.set是否有效线索("否");
                } else {
                    entity.set是否有效线索("是");
                }
                entity.set许可(license);
                entity.set顾客姓名(req.newCus);
                entity.set电话号码(req.newCusPhone);
                entity.set顾客性别("男");
                entity.set渠道("推荐");
                entity.set是否线索("是");
                entity.set导入日期(dt);
                entity.set线索创建日期(dt);
                entity.set更新账号(user);
                entity.set更新时间(ts);
                l = lsh导入名单Repository.save(entity);
            }

            //3、插入crm_explore表
            CrmExploreModel ce = new CrmExploreModel();
            ce.setCustId(Integer.valueOf(req.oldCusId));
            if (req.newSc != null) {
                ce.setNewSc(req.newSc);
            } else {
                ce.setNewSc(req.oldSc);
            }
            ce.setIsClue(req.isClue);
            if (l == null) {
                ce.setClueId(null);
            } else {
                ce.setClueId(l.get导入编号());
            }
            ce.setRemark(req.remark);
            ce.setScCheck("0");
            ce.setUpdateAccount(user);
            ce.setExploreTime(ts);
            ce.setUpdateTime(ts);
            CrmExploreModel newRecord = crmExploreRepository.save(ce);

            if (!StringUtils.isNullOrBlank(req.id)) {
                CrmHistoryModel crmHistoryModel = crmHistoryRepository.findOne(Integer.parseInt(req.id));
                if (crmHistoryModel != null) {
                    saveCrmHistory(crmHistoryModel, null, null, null, null, null, null, null, null, null, "1", null, "推荐名单推送", user);
                    saveCrmHistoryLog(null, req.id, "推荐名单推送", null, req.remark, user);
                }
            }

            //4、系统消息
            String content = "";
            String recUser = null;
            String mobile = null;
            if (null == req.newCus || "".equals(req.newCus)) {
                recUser = req.newSc;
                content = MessageContext.setScForCustomer(old顾客.get顾客姓名(), old顾客.get电话号码());
                mobile = old顾客.get电话号码();
                list.add(req.oldSc);
            } else {
                recUser = req.oldSc;
                content = MessageContext.setScForCustomer(req.newCus, req.newCusPhone);
                mobile = req.newCusPhone;
                list.add(req.newSc);
            }
            Lsh消息Model message = LshMsgUtils.getLshMsg(license, user, license, recUser,
                    "线索", content, user, mobile);

            //5、推送消息给sc
            JPush.SendPushITaskForAndroidAndIos(content, content, JsonObjectUtils.getJsonObject("", "", "", req.newCusPhone, "", ""), list);
            return true;
        } catch (Exception e) {
            logger.error("给顾客分配sc异常:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    /**
     * 首次离店、战败、休眠、nps新车交付、crm为当前用户的调研回访记录  调研列表查询
     * @param getCrmSurveyQuery
     * @param permit
     * @return
     */
    @Override
    @Transactional
    public ResultData crmSurveyQuery(GetCrmSurveyQuery getCrmSurveyQuery, String permit, String username) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());

            Lsh经销商表Model lsh经销商表Model = lsh经销商表Repository.findOne(permit);
            销售项目设置Model modelFirst = repository销售项目设置.cusFirstInAndLeaveDay(lsh经销商表Model.get大区en(), "顾客首次离店回访间隔天数");
            if (modelFirst != null) {
                calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt("-" + modelFirst.get值()));
            } else {
                modelFirst = repository销售项目设置.cusFirstInAndLeaveDay("LSH", "顾客首次离店回访间隔天数");
                if (modelFirst != null) {
                    calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt("-" + modelFirst.get值()));
                } else {
                    calendar.add(Calendar.DAY_OF_MONTH, -2);
                }
            }
            String firstToShopDate = DateFormatUtils.getFormatDateToString(calendar.getTime(), DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD);
            //重置 日期为当天
            calendar.setTime(new Date());
            销售项目设置ModelPK 销售项目设置ModelPK = new 销售项目设置ModelPK();
            销售项目设置ModelPK.set许可(permit);
            销售项目设置ModelPK.set设置项目("CRM_NPS天数");
            销售项目设置Model modelNPS = repository销售项目设置.findOne(销售项目设置ModelPK);
            if (modelNPS == null) {
                销售项目设置ModelPK.set许可(lsh经销商表Model.get大区en());
                销售项目设置ModelPK.set设置项目("新车交车后推送间隔天数");
                modelNPS = repository销售项目设置.findOne(销售项目设置ModelPK);
                if (modelNPS == null) {
                    销售项目设置ModelPK.set许可("LSH");
                    销售项目设置ModelPK.set设置项目("新车交车后推送间隔天数");
                    modelNPS = repository销售项目设置.findOne(销售项目设置ModelPK);
                }
            }
            if (modelNPS != null) {
                calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt("-" + modelNPS.get值()));
            } else {
                calendar.add(Calendar.DAY_OF_MONTH, -2);
            }
            String NPSDate = DateFormatUtils.getFormatDateToString(calendar.getTime(), DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD);

            int pageSize = getCrmSurveyQuery.getPageSize();
            int pageIndex = getCrmSurveyQuery.getPageIndex();
            int pageSizeStart =  pageIndex * pageSize;
            String stage = getCrmSurveyQuery.stage;
            int totle = 0;
            List resultList = new ArrayList();
            PageData pageData = null;

            List listCount = crmRepository.findSurveyInfoForCount(permit, username, firstToShopDate, NPSDate, getCrmSurveyQuery.stage,getCrmSurveyQuery.cusName,
                    getCrmSurveyQuery.cusPhone,getCrmSurveyQuery.researchState,getCrmSurveyQuery.connectStartDate,getCrmSurveyQuery.connectEndDate,
                    getCrmSurveyQuery.nowState,getCrmSurveyQuery.intentCarVehicles,getCrmSurveyQuery.intentCarStyle,getCrmSurveyQuery.nextConnectStartDate,
                    getCrmSurveyQuery.nextConnectEndDate, getCrmSurveyQuery.surveyResult,pageSize,pageSizeStart);
            if (listCount != null && listCount.size() > 0) {
                for (Object o: listCount) {
                    Map map = (Map) o;
                    int countNum = !StringUtils.isNullOrBlank(map.get("countNum")) ? Integer.parseInt(map.get("countNum").toString()) : 0;
                    totle += countNum;
                }
                if (StringUtils.isNullOrBlank(getCrmSurveyQuery.connectStartDate) && StringUtils.isNullOrBlank(getCrmSurveyQuery.connectEndDate)
                        && StringUtils.isNullOrBlank(getCrmSurveyQuery.nextConnectStartDate) && StringUtils.isNullOrBlank(getCrmSurveyQuery.nextConnectEndDate)
                        && StringUtils.isNullOrBlank(getCrmSurveyQuery.surveyResult)) {
                    for (int i = 1; i <= listCount.size(); i++) {
                        Map map = null;
                        if (i == listCount.size()) {
                            map = (Map) listCount.get(0);
                        } else {
                            map = (Map) listCount.get(i);
                        }
                        int countNum = !StringUtils.isNullOrBlank(map.get("countNum")) ? Integer.parseInt(map.get("countNum").toString()) : 0;
                        String state = map.get("state").toString();
                        if (countNum >= pageSizeStart + pageSize) {
                            resultList = getSurveyList (resultList, state, permit, username, firstToShopDate, NPSDate, getCrmSurveyQuery.stage, getCrmSurveyQuery.cusName,
                                    getCrmSurveyQuery.cusPhone, getCrmSurveyQuery.researchState, getCrmSurveyQuery.connectStartDate, getCrmSurveyQuery.connectEndDate,
                                    getCrmSurveyQuery.nowState, getCrmSurveyQuery.intentCarVehicles, getCrmSurveyQuery.intentCarStyle, getCrmSurveyQuery.nextConnectStartDate,
                                    getCrmSurveyQuery.nextConnectEndDate, getCrmSurveyQuery.surveyResult, pageSize, pageSizeStart);
                            break;
                        } else if (countNum < pageSizeStart + pageSize && countNum >= pageSizeStart) {
                            resultList = getSurveyList (resultList, state, permit, username, firstToShopDate, NPSDate, getCrmSurveyQuery.stage, getCrmSurveyQuery.cusName,
                                    getCrmSurveyQuery.cusPhone, getCrmSurveyQuery.researchState, getCrmSurveyQuery.connectStartDate, getCrmSurveyQuery.connectEndDate,
                                    getCrmSurveyQuery.nowState, getCrmSurveyQuery.intentCarVehicles, getCrmSurveyQuery.intentCarStyle, getCrmSurveyQuery.nextConnectStartDate,
                                    getCrmSurveyQuery.nextConnectEndDate, getCrmSurveyQuery.surveyResult, pageSize, pageSizeStart);
                            pageSize = pageSize + pageSizeStart - countNum;
                            pageSizeStart = 0;
                        } else {
                            pageSizeStart = pageSizeStart - countNum;
                        }
                    }
                } else {
                    for (int i = 0; i < surveyResultType.length; i++) {
                        if (surveyResultType[i].equals(getCrmSurveyQuery.surveyResult)) {
                            getCrmSurveyQuery.surveyResult = String.valueOf(1 + i);
                        }
                    }
                    resultList = getSurveyList (resultList, null, permit, username, firstToShopDate, NPSDate, getCrmSurveyQuery.stage, getCrmSurveyQuery.cusName,
                            getCrmSurveyQuery.cusPhone, getCrmSurveyQuery.researchState, getCrmSurveyQuery.connectStartDate, getCrmSurveyQuery.connectEndDate,
                            getCrmSurveyQuery.nowState, getCrmSurveyQuery.intentCarVehicles, getCrmSurveyQuery.intentCarStyle, getCrmSurveyQuery.nextConnectStartDate,
                            getCrmSurveyQuery.nextConnectEndDate, getCrmSurveyQuery.surveyResult, pageSize, pageSizeStart);
                }
            } else {
                logger.error("crm调研列表查询总数失败");
            }
            pageData = new PageData(resultList, totle);
            if (pageData != null) {
                resultData.setMessage(pageData.getTotal() + "");
            }
            resultData.setResult("true");
            resultData.setPageData(pageData);
        } catch (Exception e) {
            resultData.setMessage("程序异常");
            logger.error("查询调研列表异常", e);
        }
        return resultData;
    }

    private List getSurveyList (List resultList, String state, String permit, String username, String firstToShopDate, String NPSDate, String stage, String cusName,
                                String cusPhone, String researchState, String connectStartDate, String connectEndDate, String nowState,
                                String intentCarVehicles, String intentCarStyle, String nextConnectStartDate, String nextConnectEndDate,
                                String surveyResult, int pageSize, int pageSizeStart) {
        if ("firstSurvey".equals(state)) {
            resultList.addAll(crmRepository.findSurveyInfoForFirstSurvey(permit, username, firstToShopDate, NPSDate, stage, cusName,
                    cusPhone, researchState, connectStartDate, connectEndDate,
                    nowState, intentCarVehicles, intentCarStyle, nextConnectStartDate,
                    nextConnectEndDate, surveyResult, pageSize, pageSizeStart));
        } else if ("NPSSurvey".equals(state)) {
            resultList.addAll(crmRepository.findSurveyInfoForNPSSurvey(permit, username, firstToShopDate, NPSDate, stage, cusName,
                    cusPhone, researchState, connectStartDate, connectEndDate,
                    nowState, intentCarVehicles, intentCarStyle, nextConnectStartDate,
                    nextConnectEndDate, surveyResult, pageSize, pageSizeStart));
        } else if ("failOrSleepSurvey".equals(state)) {
            resultList.addAll(crmRepository.findSurveyInfoForFailOrSleepSurvey(permit, username, firstToShopDate, NPSDate, stage, cusName,
                    cusPhone, researchState, connectStartDate, connectEndDate,
                    nowState, intentCarVehicles, intentCarStyle, nextConnectStartDate,
                    nextConnectEndDate, surveyResult, pageSize, pageSizeStart));
        } else {
            resultList.addAll(crmRepository.findSurveyInfoForAlreadySurvey(permit, username, firstToShopDate, NPSDate, stage, cusName,
                    cusPhone, researchState, connectStartDate, connectEndDate,
                    nowState, intentCarVehicles, intentCarStyle, nextConnectStartDate,
                    nextConnectEndDate, surveyResult, pageSize, pageSizeStart));
        }
        return resultList;
    }


    /**
     * 查询关于集团的crm调研的项目设置
     *
     * @param stage
     * @return
     */
    @Override
    public ResultData findInstallIntervalDayAndAboutSurvey(String permit, String stage) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            Map map = new HashMap();
            if ("01".equals(stage)) {
                销售项目设置Model model1 = repository销售项目设置.cusFirstInAndLeaveDay(permit, "顾客首次离店回访间隔天数");
                销售项目设置Model model2 = repository销售项目设置.cusFirstInAndLeaveDay(permit, "更换销售顾问后首次接待是否进行调研");
                if (model1 != null) {
                    map.put("顾客首次离店回访间隔天数", model1.get值());
                } else {
                    map.put("顾客首次离店回访间隔天数", "");
                }
                if (model2 != null) {
                    map.put("更换销售顾问后首次接待是否进行调研", model2.get值());
                } else {
                    map.put("更换销售顾问后首次接待是否进行调研", "false");
                }
                List list = new ArrayList();
                list.add(map);
                resultData.setResult("true");
                resultData.setPageData(new PageData(list, 0));
            } else if ("04".equals(stage)) {
                销售项目设置Model model1 = repository销售项目设置.cusFirstInAndLeaveDay(permit, "新车交车后推送间隔天数");
                if (model1 != null) {
                    map.put("新车交车后推送间隔天数", model1.get值());
                } else {
                    map.put("新车交车后推送间隔天数", "");
                }
                List list = new ArrayList();
                list.add(map);
                resultData.setResult("true");
                resultData.setPageData(new PageData(list, 0));
            } else {
                resultData.setMessage("stage不在值域内");
            }
        } catch (Exception e) {
            logger.error("查询crm调研设置异常", e);
        }
        return resultData;
    }

    /**
     * 根据参数day，返回当前时间前day天的时间，默认时间为两天前
     * @param day
     * @return
     */
    public String returnDayNum(String day) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String returnDate = null;
        int dayNum = 0;
        if (day != null && !"".equals(day) && Integer.parseInt(day) != 0) {
            dayNum = 0 - Integer.parseInt(day);
        } else {
            dayNum = -2;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, dayNum);
        returnDate = sdf.format(calendar.getTime());
        return returnDate;
    }

    /**
     * 设置首进店离店间隔天数、更换销售顾问后首次接待是否进行调研、新车交车后推送间隔天数
     * @param day
     * @return
     */
    @Override
    @Transactional
    public ResultData installIntervalDayAndAboutSurvey(String permit, String username, String stage, String day) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            if (day != null && !"".equals(day) && Integer.parseInt(day) >= 0) {
                if ("01".equals(stage)) {
                    saleInstallIntervalDayAndAboutSurvey(permit, username, day, "顾客首次离店回访间隔天数");
                } else if ("04".equals(stage)) {
                    saleInstallIntervalDayAndAboutSurvey(permit, username, day, "新车交车后推送间隔天数");
                } else {
                    logger.error("设置首次离店调研/NPS调研,stage不在值域内,stage:" + stage);
                    resultData.setMessage("stage不在值域内");
                    return resultData;
                }
                resultData.setResult("true");
            } else {
                logger.error("设置首次离店调研/NPS调研,间隔天数设置有误,day:" + day);
                resultData.setMessage("间隔天数设置有误");
                return resultData;
            }
        } catch (Exception e) {
            resultData.setMessage("程序异常");
            logger.error("销售项目设置异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    private void saleInstallIntervalDayAndAboutSurvey (String permit, String username, String day, String install) {
        if ("LSH".equals(permit)) {
            List<销售项目设置Model> list = repository销售项目设置.findAllModelByParam(install);
            if (list != null && list.size() > 0) {
                for (销售项目设置Model model : list) {
                    model.set值(day);
                }
                repository销售项目设置.save(list);
            } else {
                销售项目设置Model model = new 销售项目设置Model();
                model.set许可(permit);
                model.set设置项目(install);
                model.set值(day);
                model.set更新账号(username);
                model.set更新时间(new Timestamp(System.currentTimeMillis()));
                repository销售项目设置.save(model);
            }
        } else {
            销售项目设置ModelPK modelPK = new 销售项目设置ModelPK();
            modelPK.set许可(permit);
            modelPK.set设置项目(install);
            销售项目设置Model model = repository销售项目设置.findOne(modelPK);
            if (model == null) {
                model = new 销售项目设置Model();
                model.set许可(permit);
                model.set设置项目(install);
                model.set值(day);
                model.set更新账号(username);
                model.set更新时间(new Timestamp(System.currentTimeMillis()));
                repository销售项目设置.save(model);
            } else {
                model.set值(day);
                repository销售项目设置.save(model);
            }
        }
    }

    @Override
    public int saveDealerNPSDayNum(String username, List<销售项目设置Model> list) {
        int result = 0;
        try {
            if (list != null && !list.isEmpty()) {
                销售项目设置Model model = list.get(0);
                model = repository销售项目设置.save(model);
                if (model != null) {
                    result = 1;
                }
            }
        } catch (Exception e) {
            logger.error("保存经销商NPS天数异常", e);
        }
        return result;
    }

    @Override
    public List findDealerNPSDayNum(销售项目设置Model model) {
        List list = new ArrayList();
        try {
            if (model != null) {
                Map map = new HashMap();
                销售项目设置ModelPK dealerModelPK = new 销售项目设置ModelPK();
                dealerModelPK.set许可(model.get许可());
                dealerModelPK.set设置项目(model.get设置项目());
                销售项目设置Model dealerModel = repository销售项目设置.findOne(dealerModelPK);

                Lsh经销商表Model lsh经销商表Model = lsh经销商表Repository.findOne(model.get许可());

                销售项目设置ModelPK groupModelPK = new 销售项目设置ModelPK();
                groupModelPK.set许可(lsh经销商表Model.get大区en());
                groupModelPK.set设置项目("新车交车后推送间隔天数");
                销售项目设置Model groupModel = repository销售项目设置.findOne(groupModelPK);
                if (groupModel == null) {
                    groupModelPK.set许可("LSH");
                    groupModelPK.set设置项目("新车交车后推送间隔天数");
                    groupModel = repository销售项目设置.findOne(groupModelPK);
                }

                map.put("设置项目", model.get设置项目());
                if (dealerModel != null) {
                    map.put("值", dealerModel.get值());
                } else {
                    map.put("值", 1);
                }
                if (groupModel != null) {
                    map.put("LSHDayNum", groupModel.get值());
                } else {
                    map.put("LSHDayNum", 2);
                }
                list.add(map);
            }
        } catch (Exception e) {
            logger.error("查询经销商设置的NPS天数异常", e);
        }
        return list;
    }

    /**
     * 插入或者修改调研介绍
     * @param permit
     * @param username
     * @param stage
     * @param intent
     * @param target
     * @return
     */
    @Override
    @Transactional
    public ResultData insertOrUpdateSurvey(String permit, String username, String stage, String intent, String target) {
        ResultData resultData = new ResultData();
        try {
            if (stage == null || "".equals(stage)) {
                resultData.setResult("false");
                resultData.setMessage("stage为空或null");
            } else if (!"01".equals(stage) && !"02".equals(stage) && !"03".equals(stage) && !"04".equals(stage)) {
                resultData.setResult("false");
                resultData.setMessage("stage不在值域内");
                return resultData;
            } else if (intent == null || "".equals(intent)) {
                resultData.setResult("false");
                resultData.setMessage("intent为空或null");
            } else if (target == null || "".equals(target)) {
                resultData.setResult("false");
                resultData.setMessage("target为空或null");
            } else {
                CrmResearchIntentModel crmResearchIntentModel = crmRearchIntentRepository.getModelByPermitAndStage(permit, stage);
                if (crmResearchIntentModel == null) {
                    crmResearchIntentModel = new CrmResearchIntentModel();
                    crmResearchIntentModel.setPermit(permit);
                    crmResearchIntentModel.setStage(stage);
                }
                crmResearchIntentModel.setIntent(intent);
                crmResearchIntentModel.setTarget(target);
                crmResearchIntentModel.setUpdateAccount(username);
                crmResearchIntentModel.setUpdateTime(new Timestamp(new Date().getTime()));
                crmRearchIntentRepository.save(crmResearchIntentModel);
                resultData.setResult("true");
            }
        } catch (Exception e) {
            resultData.setResult("false");
            resultData.setMessage("程序异常");
            logger.error("修改或添加调研介绍异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    /**
     * 查询调研介绍
     * @param permit
     * @param stage
     * @return
     */
    @Override
    @Transactional
    public ResultData surveyQuery(String permit, String stage) {
        ResultData resultData = new ResultData();
        if (stage == null || "".equals(stage)) {
            resultData.setResult("false");
            resultData.setMessage("stage为空或null");
        } else if (!"01".equals(stage) && !"02".equals(stage) && !"03".equals(stage) && !"04".equals(stage)) {
            resultData.setResult("false");
            resultData.setMessage("stage不在值域内");
            return resultData;
        }
        List list = new ArrayList();
        PageData pageData;
        CrmResearchIntentModel crmResearchIntentModel = crmRearchIntentRepository.getModelByPermitAndStage(permit, stage);
        resultData.setResult("true");
        if (crmResearchIntentModel == null) {
            crmResearchIntentModel = crmRearchIntentRepository.getModelByPermitAndStage(GetConfigureInfoUtils.getConfigureInfo("file_group"), stage);
            list.add(crmResearchIntentModel);
        } else {
            list.add(crmResearchIntentModel);
        }
        pageData = new PageData(list, 0);
        resultData.setPageData(pageData);
        return resultData;
    }

    /**
     * 查询用于调研的题库
     *
     * @param permit
     * @param stage
     * @return
     */
    @Override
    public ResultData queryTopicForSurvey(String permit, String username, String stage, String custId, String connectDate, String serialNumber, String id) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List list = new ArrayList<>();
            boolean jugdeResult = jugdeSurveyType(permit, username, stage, custId, connectDate, serialNumber, id);
            if (!jugdeResult) {
                resultData.setMessage("已有其他CRM专员对该顾客调研！");
                return resultData;
            }
            CrmHistoryModel crmHistoryModel = null;
            String groupVersion = null;
            String dealerVersion = null;
            if (!StringUtils.isNullOrBlank(id)) {
                crmHistoryModel = crmHistoryRepository.findOne(Integer.parseInt(id));
                if (crmHistoryModel != null) {
                    groupVersion = crmHistoryModel.getGroupVersion();
                    dealerVersion = crmHistoryModel.getDealerVersion();
                }
            } else {
                groupVersion = crmTopicRepository.queryMaxVersionByPermitAndSatge(GetConfigureInfoUtils.getConfigureInfo("file_group"), stage, "%DCH%");
                dealerVersion = crmTopicRepository.queryMaxVersionByPermitAndSatge(permit, stage, "%" + permit + "%");
            }
            List<CrmTopicModel> listGroup = crmTopicRepository.queryTopicByVersion(GetConfigureInfoUtils.getConfigureInfo("file_group"), stage, groupVersion);
            List<CrmTopicModel> listDealer = crmTopicRepository.queryTopicByVersion(permit, stage, dealerVersion);
            addAnswerByTopic(list, listGroup, id);
            addAnswerByTopic(list, listDealer, id);
            resultData.setResult("true");
            resultData.setPageData(new PageData(list, list.size()));
        } catch (Exception e) {
            resultData.setMessage("程序异常");
            logger.error("查询用于调研的题库及答案异常", e);
        }
        return resultData;
    }

    //查询题目对应的的答案
    private List addAnswerByTopic(List list, List<CrmTopicModel> listTopic, String historyId) throws Exception {
        List<CrmFlowModel> listFlow = null;
        if (listTopic != null && listTopic.size() == 1 && StringUtils.isNullOrBlank(listTopic.get(0).getType())) {
            return list;
        }
        if (!StringUtils.isNullOrBlank(historyId)) {
            listFlow = crmFlowRepository.findFlowByHistoryId(Integer.parseInt(historyId));
        }
        for (CrmTopicModel crmTopicModel : listTopic) {
            CrmTopicModel crmTopic = (CrmTopicModel) CloneUtils.deepClone(crmTopicModel);
            Map<String, Object> map = new HashMap<>();
            if (listFlow != null && !listFlow.isEmpty()) {
                for (CrmFlowModel crmFlowModel : listFlow) {
                    if (crmFlowModel != null && crmFlowModel.getTopicId().equals(crmTopicModel.getId())) {
                        crmTopic.setRemark(crmFlowModel.getCrmRemark());
                    }
                }
            }
            map.put("topic", crmTopic);
            List listAnswer = crmRepository.findAnswerByTopicId(crmTopicModel.getId() + "", historyId);
            map.put("answer", listAnswer);
            list.add(map);
        }
        return list;
    }

    /**
     * 查询调研的顾客的背景资料
     *
     * @param custId
     * @return
     */
    @Override
    public ResultData cusInfoWhenCrmSurvey(String permit, String username, String stage, String custId, String connectDate, String serialNumber, String id) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            boolean jugdeResult = jugdeSurveyType(permit, username, stage, custId, connectDate, serialNumber, id);
            if (!jugdeResult) {
                resultData.setMessage("已有其他CRM专员对该顾客调研！");
                return resultData;
            }
            String interfaceState = null;
            CrmHistoryModel crmHistoryModel = null;
            if (!StringUtils.isNullOrBlank(id)) {
                crmHistoryModel = crmHistoryRepository.findOne(Integer.parseInt(id));
                if (crmHistoryModel != null) {
                    if (crmHistoryModel.getSurveyResult() == null || "2".equals(crmHistoryModel.getSurveyResult()) || "6".equals(crmHistoryModel.getSurveyResult())) {
                        interfaceState = "1";
                    } else {
                        interfaceState = "0";
                    }
                } else {
                    interfaceState = "1";
                }
            } else {
                interfaceState = "1";
            }

            List<?> list = repository顾客记录汇总SQL.cusInfoWhenCrmSurvey(stage, custId, id);
            String[] array = {"", "待甄别", "待邀约", "待分配", "分配中", "分配不成功", "分配完成", "初次联系完成", "新车战败", "到店接待", "报价",
                    "待跟进", "意向金", "订金", "首付款到账", "全款到账", "合同", "零售", "交车完毕"};
            if (list != null && !list.isEmpty()) {
                Map map = (Map) list.get(0);
                map.put("interfaceState", interfaceState);
                String newCarSalesState = map.get("newCarSalesState") == null ? null : map.get("newCarSalesState").toString();
                if (newCarSalesState != null && !"".equals(newCarSalesState)) {
                    map.put("newCarSalesState", array[Integer.parseInt(newCarSalesState)]);
                }
            }
            resultData.setResult("true");
            resultData.setPageData(new PageData(list, 1));
        } catch (Exception e) {
            resultData.setMessage("程序异常");
            logger.error("查询调研的顾客的背景资料异常", e);
        }
        return resultData;
    }

    /**
     * 查询某条调研记录
     *
     * @param permit
     * @param username
     * @param stage
     * @param custId
     * @param connectDate
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData querySurveyInfo(String permit, String username, String stage, String custId, String connectDate,
                                      String serialNumber, String id) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        boolean jugdeResult = jugdeSurveyType(permit, username, stage, custId, connectDate, serialNumber, id);
        if (!jugdeResult) {
            resultData.setMessage("已有其他CRM专员对该顾客调研！");
            return resultData;
        }
        CrmHistoryModel crmHistoryModel = null;
        if (!StringUtils.isNullOrBlank(id)) {
            crmHistoryModel = crmHistoryRepository.findOne(Integer.parseInt(id));
        } else {
            String groupVersion = crmTopicRepository.queryMaxVersionByPermitAndSatge(GetConfigureInfoUtils.getConfigureInfo("file_group"), stage, "%DCH%");
            String dealerVersion = crmTopicRepository.queryMaxVersionByPermitAndSatge(permit, stage, "%" + permit + "%");
            crmHistoryModel = saveCrmHistory(crmHistoryModel, permit, stage, username, custId, null, null, null, groupVersion, dealerVersion, "0",
                    serialNumber, "", username);
            if (crmHistoryModel == null) {
                return resultData;
            }
        }
        用户Model model = repository用户.findByCode(crmHistoryModel.getCrm());
        CrmHistoryModel historyModel = (CrmHistoryModel) CloneUtils.deepClone(crmHistoryModel);
        if (model != null) {
            historyModel.setCrm(model.get人员姓名());
        }
        List list = new ArrayList();
        list.add(historyModel);
        resultData.setResult("true");
        resultData.setPageData(new PageData(list, 1));
        return resultData;
    }

//    /**
//     * 查询调研的顾客的调研历史记录
//     *
//     * @param permit
//     * @param stage
//     * @param custId
//     * @return
//     */
//    @Override
//    public ResultData querySurveyHistory(String permit, String username, String stage, String custId) {
//        ResultData resultData = new ResultData();
//        try {
//            List<CrmHistoryModel> list = crmHistoryRepository.querySurveyHistory(permit, username, stage, Integer.parseInt(custId));
//            List<CrmHistoryModel> list1 = new ArrayList<>();
//            String[] array = {"", "现在没空但是可以预约", "拒绝回访", "我没去看过车", "重新分配", "推荐名单推送", "投诉"};
//            if (list != null && !list.isEmpty()) {
//                for (CrmHistoryModel crmHistoryModel : list) {
//                    CrmHistoryModel model = (CrmHistoryModel) CloneUtils.deepClone(crmHistoryModel);
//                    if (crmHistoryModel.getOtherRemark() != null && !"".equals(crmHistoryModel.getOtherRemark())) {
//                        model.setOtherRemark(array[Integer.parseInt(model.getOtherRemark())]);
//                    }
//                    list1.add(model);
//                }
//            }
//            resultData.setResult("true");
//            resultData.setPageData(new PageData(list1, 0));
//        } catch (Exception e) {
//            resultData.setResult("false");
//            resultData.setMessage("程序异常");
//            logger.error("查询调研的顾客的调研历史记录异常", e);
//        }
//        return resultData;
//    }

    /**
     * 判断 该调研记录 是否是新的调研 还是 已有调研记录
     *
     * @param permit
     * @param username
     * @param stage
     * @param custId
     * @param connectDate
     * @return
     * @throws ParseException
     */
    private boolean jugdeSurveyType(String permit, String username, String stage, String custId, String connectDate, String serialNumber, String id) throws ParseException {
        boolean flag = false;
        CrmHistoryModel crmHistoryModel = null;
        if (!StringUtils.isNullOrBlank(id)) {
            crmHistoryModel = crmHistoryRepository.findOne(Integer.parseInt(id));
            if (crmHistoryModel != null) {
                if (username.equals(crmHistoryModel.getCrm())) {
                    flag = true;
                }
            }
        } else {
            List<CrmHistoryModel> list = null;
            if ("01".equals(stage) || "04".equals(stage)) {
                if (!StringUtils.isNullOrBlank(custId) && !StringUtils.isNullOrBlank(serialNumber)) {
                    list = crmHistoryRepository.querySurveyHistoryByPermitAndCustIdAndStageAndCrm(permit, stage, Integer.parseInt(custId), Integer.parseInt(serialNumber));
                }
            } else if ("02".equals(stage) || "03".equals(stage)) {
                list = crmHistoryRepository.querySurveyHistoryByPermitAndCustIdAndStageAndCrm(permit, stage, Integer.parseInt(custId));
            }
            if (list != null && !list.isEmpty()) {
                crmHistoryModel = list.get(0);
                if (crmHistoryModel != null && username.equals(crmHistoryModel.getUpdateAccount())) {
                    flag = true;
                }
            } else {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 保存题库调研结果
     * @param list
     * @param username
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData topicSurveyResult(List<GetTopicSurveyResult> list, String id, String username) throws Exception {
        ResultData resultData = new ResultData();
        CrmHistoryModel crmHistoryModel = crmHistoryRepository.findOne(Integer.parseInt(id));
        crmHistoryModel.setHistoryState("1");
        List<CrmFlowModel> listFlow = crmFlowRepository.findFlowByHistoryId(Integer.parseInt(id));
        crmFlowRepository.deleteInBatch(listFlow);
        List<CrmFlowModel> listCrmFlow = new ArrayList<>();
        for (GetTopicSurveyResult getTopicSurveyResult : list) {
            if (getTopicSurveyResult.remark != null && getTopicSurveyResult.remark.length() > 64) {
                return new ResultData("false", "备注信息不能超过64个字符", null);
            }

            //判断 答案id 是否为空或null ； 如果为空或null，则 校验 开放答案是否为空或null
            if (getTopicSurveyResult.answerId == null || "".equals(getTopicSurveyResult.answerId)) {
//                //判断 开放答案是否为空或null，如果为空或null，则 结束本次循环，进入下次循环
//                if (getTopicSurveyResult.openAnswer == null || "".equals(getTopicSurveyResult.openAnswer)) {
//                    continue;
//                }
//                // 开放答案 不为 空 或 null，将开放答案存入 答案表
//                CrmAnswerModel crmAnswerModel = new CrmAnswerModel();
//                crmAnswerModel.setStemId(Integer.parseInt(getTopicSurveyResult.topicId));
//                crmAnswerModel.setResponse(getTopicSurveyResult.openAnswer);
//                CrmAnswerModel crmAnswer = crmAnswerRepository.save(crmAnswerModel);
//                //校验 开放答案 是否存入 答案表，如果存入 ，将该条题目调研结果存入数据库
//                if (crmAnswer != null) {
//                    CrmFlowModel crmFlowModel = new CrmFlowModel();
//                    crmFlowModel.setTopicId(Integer.parseInt(getTopicSurveyResult.topicId));
//                    crmFlowModel.setHistoryId(Integer.parseInt(id));
//                    crmFlowModel.setUpdateAccount(username);
//                    crmFlowModel.setUpdateTime(new Timestamp(new Date().getTime()));
//                    crmFlowModel.setAnswerId(crmAnswer.getId());
//                    crmFlowModel.setCrmRemark(getTopicSurveyResult.remark);
//                    listCrmFlow.add(crmFlowModel);
//                }
                CrmFlowModel crmFlowModel = new CrmFlowModel();
                crmFlowModel.setTopicId(Integer.parseInt(getTopicSurveyResult.topicId));
                crmFlowModel.setHistoryId(Integer.parseInt(id));
                crmFlowModel.setUpdateAccount(username);
                crmFlowModel.setUpdateTime(new Timestamp(new Date().getTime()));
                crmFlowModel.setAnswerId(null);
                crmFlowModel.setCrmRemark(getTopicSurveyResult.remark);
                listCrmFlow.add(crmFlowModel);
            } else {
                // 答案id 不为空或null，则将 题目id，答案id，调研记录id存入数据库
                String[] array = getTopicSurveyResult.answerId.split(",");
                for (String answerId : array) {
                    if (answerId != null && !"".equals(answerId)) {
                        CrmFlowModel crmFlowModel = new CrmFlowModel();
                        crmFlowModel.setTopicId(Integer.parseInt(getTopicSurveyResult.topicId));
                        crmFlowModel.setHistoryId(Integer.parseInt(id));
                        crmFlowModel.setUpdateAccount(username);
                        crmFlowModel.setUpdateTime(new Timestamp(new Date().getTime()));
                        crmFlowModel.setAnswerId(Integer.parseInt(answerId));
                        crmFlowModel.setCrmRemark(getTopicSurveyResult.remark);
                        listCrmFlow.add(crmFlowModel);
                    }
                }
            }
        }
        if (listCrmFlow.size() > 0) {
            crmFlowRepository.save(listCrmFlow);
        }
        resultData.setResult("true");
        return resultData;
    }

    /**
     * 保存调研记录
     *
     * @param getSaveSurveyResult
     * @param permit
     * @param username
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData saveSurveyResult(GetSaveSurveyResult getSaveSurveyResult, String permit, String username) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        if (getSaveSurveyResult != null) {
            if (getSaveSurveyResult.remark != null && getSaveSurveyResult.remark.length() > 64) {
                resultData.setMessage("备注信息不能超过64个字符");
                return resultData;
            }
            CrmHistoryModel crmHistoryModel = crmHistoryRepository.findOne(Integer.parseInt(getSaveSurveyResult.id));
            if (crmHistoryModel != null && !StringUtils.isNullOrBlank(getSaveSurveyResult.surveyResult)) {
                String nextConnectionDate = null;
                if ("完成问卷".equals(getSaveSurveyResult.surveyResult) || "无效电话".equals(getSaveSurveyResult.surveyResult) || "拒绝回访".equals(getSaveSurveyResult.surveyResult)) {
                    saveCrmHistoryLog(null, getSaveSurveyResult.id, getSaveSurveyResult.surveyResult,
                            getSaveSurveyResult.nextConnectDate, getSaveSurveyResult.remark, username);
                } else if ("待跟进".equals(getSaveSurveyResult.surveyResult)) {
                    Timestamp nextConnectionTime = crmHistoryLogRepository.queryNextConnectionDateByHistoryId(crmHistoryModel.getId());
                    if (nextConnectionTime != null) {
                        nextConnectionDate = DateFormatUtils.getFormatDateToString(new Date(nextConnectionTime.getTime()), "yyyy-MM-dd HH:mm:ss");
                    }
                }
                saveCrmHistory(crmHistoryModel, null, null, username, null, getSaveSurveyResult.vaild, getSaveSurveyResult.remark,
                        nextConnectionDate, null, null, "1", null, getSaveSurveyResult.surveyResult, username);
            }
            resultData.setResult("true");
        }
        return resultData;
    }

    /**
     * 查询当日及以前有预约但是问卷状态=待甄别or待预约的调研信息
     *
     * @param permit
     * @param username
     * @param requestBase
     * @return
     */
    @Override
    public ResultData findNowAndOtherAboutSurvey(String permit, String username, RequestBase requestBase) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            PageData pageData = crmRepository.findNowAndOtherAboutSurvey(permit, username, requestBase);
            if (pageData != null) {
                resultData.setMessage(pageData.getTotal() + "");
            }
            resultData.setResult("true");
            resultData.setPageData(pageData);
        } catch (Exception e) {
            resultData.setMessage("程序异常");
            logger.error("查询当日及以前有预约但是问卷状态=待甄别or待预约的调研信息异常", e);
        }
        return resultData;
    }

    /**
     * 查询预约时间在当前时间和及10分钟内的调研信息
     *
     * @param permit
     * @param username
     * @param requestBase
     * @return
     */
    @Override
    public ResultData findNowAboutSurveyInTenMinutes(String permit, String username, RequestBase requestBase) {
        ResultData resultData = new ResultData("fasle", null, null);
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.MINUTE, 10);
            Timestamp nextConnectTimeStart = new Timestamp(new Date().getTime());
            Timestamp nextConnectTimeEnd = new Timestamp(calendar.getTime().getTime());
            PageData pageData = crmRepository.findNowAboutSurveyInTenMinutes(permit, username, nextConnectTimeStart, nextConnectTimeEnd, requestBase);
            if (pageData != null) {
                resultData.setMessage(pageData.getTotal() + "");
            }
            resultData.setResult("true");
            resultData.setPageData(pageData);
            if (pageData == null || pageData.getTotal() <= 0) {
                resultData.setMessage("0");
            }
        } catch (Exception e) {
            resultData.setMessage("程序异常");
            logger.error("查询预约时间在当前时间和及10分钟内的调研信息异常", e);
        }
        return resultData;
    }

    /**
     * 经销商查询题库导入日志
     *
     * @param permit
     * @return
     */
    public ResultData findTopicLogAboutDealerByPermit(String permit) {
        ResultData resultData = new ResultData();
        try {
            List<CrmTopicLogModel> list = crmTopicLogRepository.queryLogByPermit(permit);
            resultData.setResult("true");
            if (list != null && list.size() > 0) {
                resultData.setMessage(list.size() + "");
            }
            resultData.setPageData(new PageData(list, 0));
        } catch (Exception e) {
            resultData.setResult("false");
            resultData.setMessage("程序异常");
            logger.error("经销商查询题库导入日志异常", e);
        }
        return resultData;
    }

    /**
     * 集团查询题库导入日志
     *
     * @param permit
     * @return
     */
    public ResultData findTopicLogAboutGroupByPermit(String permit, String count, String startDate, String endDate) {
        ResultData resultData = new ResultData();
        try {
            String[] array = null;
            if (count != null && !"".equals(count)) {
                array = count.split(",");
            }
            List list = crmHistorySQLRepository.findTopicLogAboutGroupByPermit(array, startDate, endDate);
            resultData.setResult("true");
            int num = 0;
            if (list != null && list.size() > 0) {
                num = list.size();
            }
            resultData.setMessage(num + "");
            resultData.setPageData(new PageData(list, num));
        } catch (Exception e) {
            resultData.setResult("false");
            resultData.setMessage("程序异常");
            logger.error("集团查询题库导入日志异常", e);
        }
        return resultData;
    }

    @Override
    @Transactional
    public ResultData saveComplaint(SaveComplaintReq req, String license, String loginUser) {
        ResultData rd = new ResultData();
        try {
            if (!StringUtils.isNullOrBlank(req.id)) {
                CrmHistoryModel crmHistoryModel = crmHistoryRepository.findOne(Integer.valueOf(req.id));
                if (crmHistoryModel == null) {
                    logger.error("crm调研投诉--未找到调研记录");
                    return new ResultData("false", "crm调研投诉--未找到调研记录", null);
                }
                saveCrmHistoryLog(null, req.id, "投诉", null, req.content, loginUser);
                //修改调研信息
                crmHistoryModel = saveCrmHistory(crmHistoryModel, null, null, null, null, null, null, null, null,
                        null, "1", null, "投诉", loginUser);
            } else {
                rd.setResult("false");
                rd.setMessage("crm调研投诉失败");
            }
            CrmComplaintModel cc = new CrmComplaintModel();
            if (req.source == null) {
                cc.setSource("CRM");
            } else {
                cc.setSource(req.source);
            }
            cc.setDate(java.sql.Date.valueOf(LocalDate.now()));
            if ("Admin@lsh.com".equals(loginUser) || "Admin".equals(loginUser)) {
                cc.setLogUser(loginUser);
            } else {
                用户Model model用户 = repository用户.findOne(loginUser);
                cc.setLogUser(model用户.get角色() + " " + model用户.get人员姓名());
            }
            cc.setCustId(Integer.valueOf(req.custId));
            cc.setLogAccount(loginUser);
            cc.setTarget(req.target);
            cc.setPermit(license);
            cc.setContent(req.content);
            cc.setUpdateAccount(loginUser);
            cc.setUpdateTime(DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date()));
            CrmComplaintModel newRecord = crmComplaintRepository.save(cc);


            顾客记录汇总Model model汇总 = repository顾客记录汇总.findOne(Integer.valueOf(req.custId));
            if (StringUtils.isNullOrBlank(model汇总.get顾客姓名())) {
                model汇总.set顾客姓名("无");
            }
            if (StringUtils.isNullOrBlank(model汇总.get电话号码())) {
                model汇总.set电话号码("无");
            }
            if (model汇总 != null) {
                String content = "有新的投诉需要您处理，客户姓名：" + model汇总.get顾客姓名() + ",客户电话：" + model汇总.get电话号码();
                //给销售经理发消息
                List<用户Model> manaModelList = repository用户.findAllManager(license);
                for (用户Model mm : manaModelList) {
                    getLshMsg(license, loginUser, license, mm.get用户名(), MessageType.Type.getName(MessageType.MSG_TYPE_COMPLAINT), content, loginUser, model汇总.get电话号码());
                    List relist = new ArrayList();
                    relist.add(mm.get用户名());
                    JPush.sendPushForAndroidAndIos(content, content, JsonObjectUtils.getJsonObject("",
                            "", "", model汇总.get电话号码(), req.custId, loginUser), relist, JPush.Platforms.iMgt);
                }
            }
            rd.setResult("true");
            rd.setMessage("保存成功！");
            List list = new ArrayList();
            list.add(newRecord);
            rd.setPageData(new PageData(list, list.size()));
        } catch (Exception e) {
            rd.setResult("false");
            rd.setMessage("程序异常");
            logger.error("系统异常。", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return rd;
    }

    @Override
    public ResultData getComplaintsList(String license, RequestBase base) {
        ResultData rd = new ResultData();
        try {

            PageData pageData = crmTopicSQLRepository.getComplaintsList(license, base.getPageIndex(),
                    base.getPageSize());
            rd.setResult("true");
            rd.setMessage("获取投诉列表成功");
            rd.setPageData(pageData);
            return rd;
        } catch (Exception e) {
            logger.error("系统异常。", e);
            rd.setResult("false");
            rd.setMessage("程序异常");
            return rd;

        }


    }

    @Override
    @Transactional
    public ResultData updateComplaintById(UpdateComplaintByIdReq req, String license, String loginUser) {
        ResultData rd = new ResultData();
        try {
            CrmComplaintModel cc = crmComplaintRepository.findOne(Integer.valueOf(req.id));
            if (cc == null) {
                rd.setResult("false");
                rd.setMessage("数据库没有此id的投诉信息");
                return rd;
            }
            cc.setUpdateTime(DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date()));
            cc.setUpdateAccount(loginUser);
            cc.setResult(req.result);
            cc.setFeedbackDate(java.sql.Date.valueOf(LocalDate.now()));
            cc.setFeedbackAccount(loginUser);
            用户Model model用户 = repository用户.findOne(loginUser);
            if (model用户 == null) {
                rd.setResult("false");
                rd.setMessage("当前登录账号不存在!");
                return rd;
            }
            cc.setFeedbackUser(model用户.get角色() + " " + model用户.get人员姓名());
            crmComplaintRepository.save(cc);
            rd.setResult("true");
            rd.setMessage("保存处理结果成功!");
            return rd;
        } catch (Exception e) {
            logger.error("系统异常。", e);
            rd.setResult("false");
            rd.setMessage("保存处理结果异常!");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return rd;
        }
    }

    /**
     * 根据许可查询题库所有版本号
     *
     * @param permit
     * @return
     */
    public ResultData findVersion(String permit) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List list = crmTopicSQLRepository.findVersion(permit);
            if (list != null && !list.isEmpty()) {
                resultData.setMessage(list.size() + "");
            }
            resultData.setResult("true");
            resultData.setPageData(new PageData(list, 0));
        } catch (Exception e) {
            resultData.setMessage("查询题库版本号程序异常");
            logger.error("查询题库版本号程序异常", e);
        }
        return resultData;
    }

    /**
     * 导出经销商题库调研结果
     * @param permit
     * @param version
     * @param connectDateStart
     * @param connectDateEnd
     * @param response
     */
    public void exportDealerSurveyResult(String permit, String version, String connectDateStart, String connectDateEnd, HttpServletResponse response) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/调研问卷结果.xlsx")
                    .setFileName("调研问卷结果.xlsx")
                    .setSource(ExportDealerSurveyResultSource)
                    .setStaticSheet(false)
                    .addParam("permit", permit)         //经销商许可
                    .addParam("version", version)       //选择的题库版本号（可不传，不传导出该许可下所有题库版本号的题库调研结果）
                    .addParam("connectDateStart", connectDateStart)
                    .addParam("connectDateEnd", connectDateEnd);

            excelReportService.export(context, response);
        } catch (Exception e) {
            logger.error("导出经销商题库调研结果异常", e);
        }
    }

    /**
     * 导出集团题库调研结果
     *
     * @param area
     * @param version
     * @param connectDateStart
     * @param connectDateEnd
     * @param response
     */
    public void exportGroupSurveyResult(String area, String version, String connectDateStart, String connectDateEnd, HttpServletResponse response) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/调研问卷结果.xlsx")
                    .setFileName("调研问卷结果.xlsx")
                    .setSource(ExportGroupSurveyResultSource)
                    .setStaticSheet(false)
                    .addParam("area", area)             //导出筛选 区域，可不传，不传默认为所有区域
                    .addParam("version", version)       //选择的题库版本号（可不传，不传导出该许可下所有题库版本号的题库调研结果）
                    .addParam("connectDateStart", connectDateStart)
                    .addParam("connectDateEnd", connectDateEnd);

            excelReportService.export(context, response);
        } catch (Exception e) {
            logger.error("导出集团题库调研结果异常", e);
        }
    }


    @Override
    public ResultData getComplaints(GetComplaintsReq req) {
        ResultData rd = new ResultData();
        try {
            List<CrmComplaintModel> list = crmComplaintRepository.getComplaintByPermitAndCustId(req.permit, Integer.valueOf(req.custId));
            if (list.size() > 0) {
                CrmComplaintModel c = list.get(0);
                rd.setMessage("查询投诉信息成功");
                rd.setResult("true");
                List l = new ArrayList();
                l.add(c);
                rd.setPageData(new PageData(l, 0));
                return rd;
            } else {
                rd.setMessage("nodata");
                rd.setResult("true");
                rd.setPageData(new PageData(null, 0));
                return rd;
            }

        } catch (Exception e) {
            logger.error("查询投诉信息出错", e);
            rd.setResult("false");
            rd.setMessage("查询投诉信息出错");
            return rd;
        }
    }

    @Override
    public ResultData findLiVEClue(String permit, GetLiVEClue getLiVEClue) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            PageData pageData = crmRepository.findLiVEClue(permit, getLiVEClue.createDateStart, getLiVEClue.createDateEnd, getLiVEClue.lastFollowDateStart,
                    getLiVEClue.lastFollowDateEnd, getLiVEClue.state, getLiVEClue.intentCarLevel, getLiVEClue.intentCarStyle, getLiVEClue.getPageSize(), getLiVEClue.getPageIndex());
            resultData.setResult("true");
            if (pageData != null) {
                resultData.setMessage(pageData.getTotal() + "");
            }
            resultData.setPageData(pageData);
        } catch (Exception e) {
            resultData.setMessage("LiVE线索导出失败");
            logger.error("LiVE线索导出失败", e);
        }
        return resultData;
    }

    @Override
    public ResultData queryVisitNum(String permit, String username, String stage) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            int dayNum = 0;
            int weekNum = 0;
            int monthNum = 0;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            java.sql.Date dayDate = new java.sql.Date(new Date().getTime());

            java.sql.Date weekStartDate = new java.sql.Date(getWeekStartTime().getTime());
            java.sql.Date weekEndDate = new java.sql.Date(getWeekEndTime().getTime());

            java.sql.Date monthStartDate = new java.sql.Date(getMonthStartTime().getTime());
            java.sql.Date monthEndDate = new java.sql.Date(getMonthEndTime().getTime());
            if (stage == null || "".equals(stage) || "00".equals(stage)) {
                dayNum = crmHistoryRepository.queryVisitNum(permit, username, dayDate, dayDate);
                weekNum = crmHistoryRepository.queryVisitNum(permit, username, weekStartDate, weekEndDate);
                monthNum = crmHistoryRepository.queryVisitNum(permit, username, monthStartDate, monthEndDate);
            } else {
                dayNum = crmHistoryRepository.queryVisitNumByStage(permit, username, stage, dayDate, dayDate);
                weekNum = crmHistoryRepository.queryVisitNumByStage(permit, username, stage, weekStartDate, weekEndDate);
                monthNum = crmHistoryRepository.queryVisitNumByStage(permit, username, stage, monthStartDate, monthEndDate);
            }
            Map map = new HashMap();
            map.put("dayNum", dayNum);
            map.put("weekNum", weekNum);
            map.put("monthNum", monthNum);
            List list = new ArrayList();
            list.add(map);
            resultData.setResult("true");
            resultData.setPageData(new PageData(list, 0));
        } catch (Exception e) {
            resultData.setMessage("查询CRM回访数异常");
            logger.error("查询CRM回访数异常", e);
        }
        return resultData;
    }

    @Override
    public void exportLiveClueSource(String permit, String createDateStart, String createDateEnd, String lastFollowDateStart,
                                     String lastFollowDateEnd, String state, String intentCarLevel, String intentCarStyle, int pageSize, int pageIndex, HttpServletResponse response) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/线索信息.xlsx")
                    .setFileName("线索信息.xlsx")
                    .setSource(ExportLiveClueSource)
                    .setStaticSheet(false)
                    .setStartCellIndex(0)
                    .setEndCellIndex(52)
                    .setAutoRowExtended(true)
                    .addParam("permit", permit)
                    .addParam("createDateStart", createDateStart)
                    .addParam("createDateEnd", createDateEnd)
                    .addParam("lastFollowDateStart", lastFollowDateStart)
                    .addParam("lastFollowDateEnd", lastFollowDateEnd)
                    .addParam("state", state)
                    .addParam("intentCarLevel", intentCarLevel)
                    .addParam("intentCarStyle", intentCarStyle)
                    .addParam("pageSize", pageSize)
                    .addParam("pageIndex", pageIndex);

            excelReportService.export(context, response);
        } catch (Exception e) {
            logger.error("导出线索信息异常", e);
        }
    }

    // 获得本周星期一0点时间
    private Date getWeekStartTime() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Date date = cal.getTime();
        return date;
    }

    // 获得本周星期日24点时间
    private Date getWeekEndTime() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.DATE, cal.get(Calendar.DATE) + 6);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        Date date = cal.getTime();
        return date;
    }

    // 获得本月第一天0点时间
    private Date getMonthStartTime() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        return cal.getTime();
    }

    // 获得本月最后一天24点时间
    private Date getMonthEndTime() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.HOUR_OF_DAY, 24);
        return cal.getTime();
    }

    @Override
    public ResultData queryRateAboutSurveyTopic(String permit, GetQueryRateAboutSurveyTopic getQueryRateAboutSurveyTopic) {
        ResultData resultData = new ResultData("false", null, null);
        if (getQueryRateAboutSurveyTopic != null) {
            String stage = getQueryRateAboutSurveyTopic.stage;
            if (stage == null || "".equals(stage)) {
                resultData.setMessage("请选择调研类型");
                return resultData;
            }
            String startDate = getQueryRateAboutSurveyTopic.startDate;
            if (startDate == null || "".equals(startDate)) {
                resultData.setMessage("请选择开始时间");
                return resultData;
            }
            String endDate = getQueryRateAboutSurveyTopic.endDate;
            if (endDate == null || "".equals(endDate)) {
                resultData.setMessage("请选择结束时间");
                return resultData;
            }
            String groupVersion = getQueryRateAboutSurveyTopic.groupVersion;
            String dealerVersion = getQueryRateAboutSurveyTopic.dealerVersion;
            try {
                List resultList = new ArrayList();
                List listAll = crmRepository.queryRateAboutSurveyTopicOfAll(permit, stage, startDate, endDate, groupVersion, dealerVersion);
                if (listAll == null || listAll.isEmpty()) {
                    resultData.setMessage("该题库未被调研过");
                } else {
                    List listSC = crmRepository.queryRateAboutSurveyTopicOfSC(permit, stage, startDate, endDate, groupVersion, dealerVersion);
                    for (Object o : listAll) {
                        Map map = (Map) o;
                        String stemId = map.get("topicId") == null ? null : map.get("topicId").toString();
                        if (stemId == null || "".equals(stemId)) {
                            resultData.setMessage("未找到相应题目编号");
                            return resultData;
                        }
                        List listAnswer = crmAnswerRepository.queryAnswerByTopicId(Integer.parseInt(stemId));
                        List<ItemsVo> list = new ArrayList<ItemsVo>();
                        //一层对象
                        ReportVo reportVo = new ReportVo();
                        reportVo.setTitle(map.get("stem") == null ? null : map.get("stem").toString());

                        //截取二层数组
                        String responses = map.get("responses") == null ? "" : map.get("responses").toString();
                        String rates = map.get("rates") == null ? "" : map.get("rates").toString();
                        list = getResult(list, responses, rates, null, "全部", listAnswer);

                        for (Object i : listSC) {
                            Map item = (Map) i;
                            String topicId = item.get("topicId") == null ? null : item.get("topicId").toString();
                            if (stemId.equals(topicId)) {
                                String answerIds = item.get("answerIds") == null ? null : item.get("answerIds").toString();
                                String rateSCs = item.get("rates") == null ? null : item.get("rates").toString();
                                String scNameSCs = item.get("scNames") == null ? null : item.get("scNames").toString();
                                list = getResult(list, answerIds, rateSCs, scNameSCs, null, listAnswer);

                            }
                        }
                        //装载第一层数组
                        reportVo.setShowData(list);
                        resultList.add(reportVo);
                    }
                }
                resultData.setResult("true");
                resultData.setPageData(new PageData(resultList, 0));
            } catch (Exception e) {
                logger.error("查询题库调研各销售顾问下线索的选择所占比率异常", e);
            }
        }
        return resultData;
    }


    private List getResult(List list, String responses, String rates, String scNames, String state, List<CrmAnswerModel> listAnswer) {

        //截取二层数组
        String[] responseArray = responses.split("___MARK___");
        String[] rateArray = rates.split("___MARK___");

        //谨防数组长度不一数组越界
        if (responseArray.length != rateArray.length) {
            //返回错误信息
        }
        if ("全部".equals(state)) {
            ItemsVo itemsVo = new ItemsVo();
            List<Map<String, String>> nodeList = new ArrayList<Map<String, String>>();
            for (int n = 0; n < responseArray.length; n++) {
                Map<String, String> nodeMap = new HashMap<String, String>();
                nodeMap.put("name", responseArray[n]);
                nodeMap.put("scale", rateArray[n]);
                nodeList.add(nodeMap);
            }
            itemsVo.setScName("全部");
            //装载第二层数组
            itemsVo.setAnswers(nodeList);
            list.add(itemsVo);
        } else {
            String[] scNameArray = scNames.split("___MARK___");
            for (int n = 0; n < scNameArray.length; n++) {
                List<Map<String, String>> nodeList = new ArrayList<Map<String, String>>();
                ItemsVo itemsVo = new ItemsVo();
                itemsVo.setScName(scNameArray[n]);
                String[] answerIdSCs = responseArray[n].split(",");
                String[] rateSCs = rateArray[n].split(",");
                for (CrmAnswerModel crmAnswerModel : listAnswer) {
                    Map<String, String> nodeMap = new HashMap<String, String>();
                    nodeMap.put("name", crmAnswerModel.getResponse());
                    nodeMap.put("scale", "0");
                    for (int i = 0; i < answerIdSCs.length; i++) {
                        if ((crmAnswerModel.getId() + "").equals(answerIdSCs[i])) {
                            nodeMap.put("scale", rateSCs[i]);
                            continue;
                        }
                    }
                    nodeList.add(nodeMap);
                }
                //装载第二层数组
                itemsVo.setAnswers(nodeList);
                list.add(itemsVo);
            }
        }

        return list;
    }

    public ResultData queryVersionAboutSurveyTopicForGroup(String permit, GetQueryRateAboutSurveyTopic getQueryRateAboutSurveyTopic) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            if (getQueryRateAboutSurveyTopic != null) {
                String stage = getQueryRateAboutSurveyTopic.stage;
                if (stage == null || "".equals(stage)) {
                    resultData.setMessage("请选择调研类型");
                    return resultData;
                }
                String startDate = getQueryRateAboutSurveyTopic.startDate;
                String endDate = getQueryRateAboutSurveyTopic.endDate;
                List list = crmRepository.queryVersionAboutSurveyTopicForGroup(permit, stage, startDate, endDate);
                resultData.setResult("true");
                if (list != null && !list.isEmpty()) {
                    resultData.setMessage(list.size() + "");
                }
                resultData.setPageData(new PageData(list, 0));
            }
        } catch (Exception e) {
            logger.error("获取调研记录中集团版本号异常");
        }
        return resultData;
    }

    public ResultData queryVersionAboutSurveyTopicForDealer(String permit, GetQueryRateAboutSurveyTopic getQueryRateAboutSurveyTopic) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            if (getQueryRateAboutSurveyTopic != null) {
                String stage = getQueryRateAboutSurveyTopic.stage;
                if (stage == null || "".equals(stage)) {
                    resultData.setMessage("请选择调研类型");
                    return resultData;
                }
                String startDate = getQueryRateAboutSurveyTopic.startDate;
                String endDate = getQueryRateAboutSurveyTopic.endDate;
                String groupVersion = getQueryRateAboutSurveyTopic.groupVersion;
                List list = crmRepository.queryVersionAboutSurveyTopicForDealer(permit, stage, startDate, endDate, groupVersion);
                resultData.setResult("true");
                if (list != null && !list.isEmpty()) {
                    resultData.setMessage(list.size() + "");
                }
                resultData.setPageData(new PageData(list, 0));
            }
        } catch (Exception e) {
            logger.error("获取调研记录中经销商版本号异常");
        }
        return resultData;
    }

    @Override
    public void exportCRMSurvey(String permit, String username, CRMService.GetCrmSurveyQuery getCrmSurveyQuery, HttpServletRequest request, HttpServletResponse response) {
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Lsh经销商表Model lsh经销商表Model = lsh经销商表Repository.findOne(permit);

            销售项目设置Model modelFirst = repository销售项目设置.cusFirstInAndLeaveDay(lsh经销商表Model.get大区en(), "顾客首次离店回访间隔天数");
            if (modelFirst != null) {
                calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt("-" + modelFirst.get值()));
            } else {
                modelFirst = repository销售项目设置.cusFirstInAndLeaveDay("LSH", "顾客首次离店回访间隔天数");
                if (modelFirst != null) {
                    calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt("-" + modelFirst.get值()));
                } else {
                    calendar.add(Calendar.DAY_OF_MONTH, -2);
                }
            }
            String firstToShopDate = sdf.format(calendar.getTime());

            销售项目设置ModelPK 销售项目设置ModelPK = new 销售项目设置ModelPK();
            销售项目设置ModelPK.set许可(permit);
            销售项目设置ModelPK.set设置项目("CRM_NPS天数");
            销售项目设置Model modelNPS = repository销售项目设置.findOne(销售项目设置ModelPK);
            if (modelNPS == null) {
                销售项目设置ModelPK.set许可(lsh经销商表Model.get大区en());
                销售项目设置ModelPK.set设置项目("新车交车后推送间隔天数");
                modelNPS = repository销售项目设置.findOne(销售项目设置ModelPK);
                if (modelNPS == null) {
                    销售项目设置ModelPK.set许可("LSH");
                    销售项目设置ModelPK.set设置项目("新车交车后推送间隔天数");
                    modelNPS = repository销售项目设置.findOne(销售项目设置ModelPK);
                }
            }
            if (modelNPS != null) {
                calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt("-" + modelNPS.get值()));
            } else {
                calendar.add(Calendar.DAY_OF_MONTH, -2);
            }
            String NSPDate = sdf.format(calendar.getTime());

            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/调研问卷信息.xlsx")
                    .setFileName("1.xlsx")
                    .setSource(ExportCRMSurveySource)
                    .setStaticSheet(false)
                    .setStartCellIndex(0)
                    .setEndCellIndex(15)
                    .setAutoRowExtended(true)
                    .addParam("permit", permit)
                    .addParam("username", username)
                    .addParam("stage", getCrmSurveyQuery.stage)
                    .addParam("cusName", getCrmSurveyQuery.cusName)
                    .addParam("cusPhone", getCrmSurveyQuery.cusPhone)
                    .addParam("researchState", getCrmSurveyQuery.researchState)
                    .addParam("connectStartDate", getCrmSurveyQuery.connectStartDate)
                    .addParam("connectEndDate", getCrmSurveyQuery.connectEndDate)
                    .addParam("nowState", getCrmSurveyQuery.nowState)
                    .addParam("intentCarStyle", getCrmSurveyQuery.intentCarStyle)
                    .addParam("intentCarVehicles", getCrmSurveyQuery.intentCarVehicles)
                    .addParam("nextConnectStartDate", getCrmSurveyQuery.nextConnectStartDate)
                    .addParam("nextConnectEndDate", getCrmSurveyQuery.nextConnectEndDate)
                    .addParam("firstToShopDate", firstToShopDate)
                    .addParam("NSPDate", NSPDate)
                    .addParam("pageSize", getCrmSurveyQuery.getPageSize())
                    .addParam("pageIndex", getCrmSurveyQuery.getPageIndex());

            excelReportService.export(context, response);
        } catch (Exception e) {
            logger.error("导出线索信息异常", e);
        }
    }

    public ResultData getSurveyResultByStage(String stage) {
        ResultData resultData = new ResultData("false", null, null);
        Map map1 = new HashMap(),
                map2 = new HashMap(),
                map3 = new HashMap(),
                map4 = new HashMap(),
                map5 = new HashMap(),
                map6 = new HashMap(),
                map7 = new HashMap(),
                map8 = new HashMap();
        map1.put("调研结果", "完成问卷");
        map2.put("调研结果", "待跟进");
        map3.put("调研结果", "无效电话");
        map4.put("调研结果", "拒绝回访");
        map5.put("调研结果", "重新分配");
        map6.put("调研结果", "投诉");
        map7.put("调研结果", "激活并分配");
        map8.put("调研结果", "推荐名单推送");
        List list = new ArrayList();
        if ("01".equals(stage)) {
            list.add(map1);
            list.add(map2);
            list.add(map3);
            list.add(map4);
            list.add(map5);
            list.add(map6);
            resultData.setResult("true");
            resultData.setPageData(new PageData(list, 1));
        } else if ("02".equals(stage)) {
            list.add(map1);
            list.add(map2);
            list.add(map3);
            list.add(map4);
            list.add(map5);
            list.add(map6);
            resultData.setResult("true");
            resultData.setPageData(new PageData(list, 1));
        } else if ("03".equals(stage)) {
            list.add(map1);
            list.add(map2);
            list.add(map3);
            list.add(map4);
            list.add(map7);
            list.add(map6);
            resultData.setResult("true");
            resultData.setPageData(new PageData(list, 1));
        } else if ("04".equals(stage)) {
            list.add(map1);
            list.add(map2);
            list.add(map3);
            list.add(map4);
            list.add(map6);
            list.add(map8);
            resultData.setResult("true");
            resultData.setPageData(new PageData(list, 1));
        } else if (stage == null || "".equals(stage) || "00".equals(stage)) {
            list.add(map1);
            list.add(map2);
            list.add(map3);
            list.add(map4);
            list.add(map5);
            list.add(map6);
            list.add(map7);
            list.add(map8);
            resultData.setResult("true");
            resultData.setPageData(new PageData(list, 1));
        } else {
            resultData.setMessage("调研类型错误");
        }
        return resultData;
    }

    @Override
    public List getSurveyLogByHistoryId (String historyId) {
        List list = null;
        if (!StringUtils.isNullOrBlank(historyId)) {
            list = crmRepository.queryCrmHistoryLogInfo(historyId);
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData crmRedistribution(String permit, String username, GetSurveyResultInfo getSurveyResultInfo) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        if (getSurveyResultInfo != null && !StringUtils.isNullOrBlank(getSurveyResultInfo.id)) {
            if (getSurveyResultInfo.reason != null && StringUtils.isNullOrBlank(getSurveyResultInfo.reason.trim())) {
                resultData.setMessage("重新分配原因不能全是空格");
                return resultData;
            }
            //获取 调研 信息
            CrmHistoryModel crmHistoryModel = crmHistoryRepository.findOne(Integer.parseInt(getSurveyResultInfo.id));
            if (crmHistoryModel != null) {
                //修改调研信息
                crmHistoryModel = saveCrmHistory(crmHistoryModel, null, null, null, null, null, null, null, null,
                        null, "1", null, getSurveyResultInfo.resultType, username);
                //获取顾客编号
                int custId = crmHistoryModel.getCustId();
                顾客记录汇总Model model = repository顾客记录汇总.findOne(custId);
                if (model != null) {
                    //重新分配--顾客状态改为 本月，crm战败确认改为 1（待分配）
                    model.setCrm战败确认(1);
                    model.set顾客状态("本月");
                    model.set更新账号(username);
                    model.set更新时间(new Timestamp(new Date().getTime()));
                    repository顾客记录汇总.save(model);
                }
                //记录调研日志
                CrmHistoryLogModel crmHistoryLogModel = saveCrmHistoryLog(null, getSurveyResultInfo.id,
                        "重新分配", null, getSurveyResultInfo.reason, username);
                //查询该许可下所有的销售经理
                List<用户Model> list = repository用户.findAllManager(model.get许可());
                List listUsername = new ArrayList();
                if (list != null && !list.isEmpty()) {
                    String messageContext = getSurveyResultInfo.message + "原因是" + getSurveyResultInfo.reason;
                    for (用户Model model用户 : list) {
                        //给 销售经理 发送信息
                        Lsh消息Model message = LshMsgUtils.getLshMsg(permit, username, model用户.get许可(), model用户.get用户名(),
                                "线索", messageContext, username, model.get电话号码());
                        //编辑 极光推送 发送信息的 接收人
                        listUsername.add(model用户.get用户名());
                    }
                    JsonObject json = JsonObjectUtils.getJsonObject("线索", null, null, model.get电话号码(), model.get顾客编号() + "",
                            model.get所属销售顾问());
                    JPush.SendPushITaskForAndroidAndIos(messageContext, messageContext, json, listUsername);
                }
                if (crmHistoryLogModel != null) {
                    resultData.setResult("true");
                }
            }
        }
        return resultData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData crmActivationAndDistribution (String permit, String username, GetSurveyResultInfo getSurveyResultInfo)  throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        if (getSurveyResultInfo != null && !StringUtils.isNullOrBlank(getSurveyResultInfo.id)) {
            //获取 调研 信息
            CrmHistoryModel crmHistoryModel = crmHistoryRepository.findOne(Integer.parseInt(getSurveyResultInfo.id));
            if (crmHistoryModel != null) {
                //修改调研信息
                crmHistoryModel = saveCrmHistory(crmHistoryModel, null, null, null, null, null, null, null, null,
                        null, "1", null, "激活并分配", username);
                //获取顾客编号
                int custId = crmHistoryModel.getCustId();
                顾客记录汇总Model model = repository顾客记录汇总.findOne(custId);
                if (model != null) {
                    int actualClueNum = 0;
                    int clueSuperiorLimit = 0;
                    if (!StringUtils.isNullOrBlank(model.get所属销售顾问())) {
                        用户Model 用户Model = repository用户.findByCode(model.get所属销售顾问());
                        if (用户Model != null && !"已删除".equals(用户Model.get删除状态()) && !"离职".equals(用户Model.get销售顾问职位状态())) {
                            List list = salesClueSetRepository.querySalesClueNum(permit, model.get所属销售顾问());
                            if (list == null || list.isEmpty() || StringUtils.isNullOrBlank(((Map) list.get(0)).get("counts"))) {
                                logger.error("crm激活并分配未获取到销售顾问线索数");
                                resultData.setMessage("crm激活并分配未获取到销售顾问线索数");
                                return resultData;
                            }
                            actualClueNum = Integer.parseInt(((Map) list.get(0)).get("counts").toString());
                            销售项目设置ModelPK modelPK = new 销售项目设置ModelPK();
                            modelPK.set许可(permit);
                            modelPK.set设置项目("线索总数上限");
                            销售项目设置Model 销售项目设置Model = repository销售项目设置.findOne(modelPK);
                            if (销售项目设置Model != null && !StringUtils.isNullOrBlank(销售项目设置Model.get值())) {
                                clueSuperiorLimit = Integer.parseInt(销售项目设置Model.get值());
                            } else {
                                clueSuperiorLimit = 120;
                            }
                        }
                    }
                    if (actualClueNum < clueSuperiorLimit) {
                        model.setCrm战败确认(2);
                        model.set顾客状态("本月");
                        repository顾客记录汇总.save(model);
                    } else {
                        model.setCrm战败确认(2);
                        repository顾客记录汇总.save(model);
                        List listLeaningIn = repository顾客记录汇总SQL.findLshLeandingInByPhoneAndPermit(model.get电话号码(), permit);
                        Lsh导入名单Model lsh导入名单Model = new Lsh导入名单Model();
                        lsh导入名单Model.set许可(permit);
                        lsh导入名单Model.set顾客姓名(model.get顾客姓名());
                        lsh导入名单Model.set顾客性别(model.get顾客性别());
                        lsh导入名单Model.set电话号码(model.get电话号码());
                        lsh导入名单Model.set渠道(model.get顾客渠道());
                        //lsh导入名单Model.set来源(model.get顾客来源());
                        lsh导入名单Model.set导入日期(new java.sql.Date(new Date().getTime()));
                        lsh导入名单Model.set线索创建日期(new java.sql.Date(new Date().getTime()));
                        lsh导入名单Model.set更新账号(username);
                        lsh导入名单Model.set更新时间(new Timestamp(new Date().getTime()));
                        lsh导入名单Model.setInfoSource("CRM");
                        lsh导入名单Model.set是否线索("是");
                        if (listLeaningIn != null && !listLeaningIn.isEmpty()) {
                            lsh导入名单Model.set是否有效线索("否");
                        } else {
                            lsh导入名单Model.set是否有效线索("是");
                        }
                        lsh导入名单Repository.save(lsh导入名单Model);
                    }
                }
                //记录调研日志
                CrmHistoryLogModel crmHistoryLogModel = saveCrmHistoryLog(null, getSurveyResultInfo.id,
                        "激活并分配", null, getSurveyResultInfo.reason, username);

                if (crmHistoryLogModel != null) {
                    resultData.setResult("true");
                }
            }
        }
        return  resultData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultData crmFollowUp (String permit, String username, GetSurveyResultInfo getSurveyResultInfo) throws Exception {
        ResultData resultData = new ResultData("false", null, null);
        if (getSurveyResultInfo != null && !StringUtils.isNullOrBlank(getSurveyResultInfo.id)
                && !StringUtils.isNullOrBlank(getSurveyResultInfo.nextConnectDate)) {
            if (getSurveyResultInfo.reason != null && getSurveyResultInfo.reason.length() > 64) {
                resultData.setMessage("备注信息不能超过64个字符");
                return resultData;
            }
            CrmHistoryModel crmHistoryModel = crmHistoryRepository.findOne(Integer.parseInt(getSurveyResultInfo.id));
            if (crmHistoryModel == null) {
                logger.error("crm调研跟进--未找到调研记录");
                return new ResultData("false", "crm调研跟进--未找到调研记录", null);
            }
            //保存调研日志
            CrmHistoryLogModel crmHistoryLogModel = saveCrmHistoryLog(null, getSurveyResultInfo.id,
                    "待跟进", getSurveyResultInfo.nextConnectDate, getSurveyResultInfo.reason, username);
            //修改调研信息
            saveCrmHistory(crmHistoryModel, null, null, null, null, null, null, getSurveyResultInfo.nextConnectDate, null,
                    null, "1", null, "待跟进", username);
            if (crmHistoryLogModel != null) {
                resultData.setResult("true");
            }
        }
        return resultData;
    }

    @Override
    public ResultData crmExportVoidQuestion (String stage, String permit, String username) throws Exception {
        ResultData resultData = new ResultData("false", null, null);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateString = sdf.format(new Date());
        int versionNum = crmTopicSQLRepository.findCurrentVersionNum(stage, "%" + dateString + "%");
        String version = null;
        //生成题库版本号
        if (GetConfigureInfoUtils.getConfigureInfo("file_group").equals(permit)) {
            version = "DCH-";
        } else {
            version = permit + "-";
        }
        if ("01".equals(stage)) {
            version = version + "SCLD-";
        } else if ("02".equals(stage)) {
            version = version + "XMDY-";
        } else if ("03".equals(stage)) {
            version = version + "ZBDY-";
        } else if ("04".equals(stage)) {
            version = version + "NPSDY-";
        } else {
            resultData.setMessage("stage不在规定值域内");
            return resultData;
        }
        if (versionNum < 9) {
            version = version + dateString + "00" + (versionNum + 1);
        } else if (versionNum < 99) {
            version = version + dateString + "0" + (versionNum + 1);
        } else {
            version = version + dateString + (versionNum + 1);
        }
        //保存一条调研题库，除许可、调研类型、版本号，其他字段都为空；
        CrmTopicModel crmTopicModel = new CrmTopicModel();
        crmTopicModel.setPermit(permit);
        crmTopicModel.setStage(stage);
        crmTopicModel.setVersion(version);
        crmTopicRepository.save(crmTopicModel);
        //保存日志
        CrmTopicLogModel crmTopicLogModel = new CrmTopicLogModel();
        crmTopicLogModel.setPermit(permit);
        crmTopicLogModel.setVersion(version);
        crmTopicLogModel.setUpdateSendInfoDate(new java.sql.Date(new Date().getTime()));
        crmTopicLogModel.setUpdateTime(new Timestamp(new Date().getTime()));
        crmTopicLogModel.setUpdateAccount(username);
        crmTopicLogRepository.save(crmTopicLogModel);
        resultData.setResult("true");
        resultData.setMessage(version);
        return resultData;
    }

    /**
     *  保存调研信息
     * @param permit
     * @param stage
     * @param crm
     * @param vaild
     * @param remark
     * @param nextConnectDate
     * @param groupVersion
     * @param dealerVersion
     * @param historyState
     * @param serialNumber
     * @param surveyResult
     * @param updateAccount
     * @return
     */
    private CrmHistoryModel saveCrmHistory(CrmHistoryModel crmHistoryModel, String permit, String stage, String crm, String custId, String vaild,
                                           String remark, String nextConnectDate, String groupVersion, String dealerVersion,
                                           String historyState, String serialNumber, String surveyResult,String updateAccount) {
        if (crmHistoryModel == null) {
            crmHistoryModel = new CrmHistoryModel();
        }
        if (!StringUtils.isNullOrBlank(permit)) {
            crmHistoryModel.setPermit(permit);
        }
        if (!StringUtils.isNullOrBlank(stage)) {
            crmHistoryModel.setStage(stage);
        }
        if (!StringUtils.isNullOrBlank(crm)) {
            crmHistoryModel.setCrm(crm);
        }
        if (!StringUtils.isNullOrBlank(custId)) {
            crmHistoryModel.setCustId(Integer.parseInt(custId));
        }
        if (!StringUtils.isNullOrBlank(vaild)) {
            if ("有效".equals(vaild)) {
                crmHistoryModel.setValid("1");
            } else if ("无效".equals(vaild)) {
                crmHistoryModel.setValid("0");
            } else {
                crmHistoryModel.setValid(vaild);
            }
        }
        if (!StringUtils.isNullOrBlank(remark)) {
            crmHistoryModel.setRemark(remark);
        }
        if (!StringUtils.isNullOrBlank(nextConnectDate)) {
            crmHistoryModel.setNextConnectDate(new Timestamp(DateFormatUtils.getFormatDate(nextConnectDate, "yyyy-MM-dd HH:mm:ss").getTime()));
        }
        if (!StringUtils.isNullOrBlank(groupVersion)) {
            crmHistoryModel.setGroupVersion(groupVersion);
        }
        if (!StringUtils.isNullOrBlank(dealerVersion)) {
            crmHistoryModel.setDealerVersion(dealerVersion);
        }
        if (!StringUtils.isNullOrBlank(historyState)) {
            crmHistoryModel.setHistoryState(historyState);
        }
        if (!StringUtils.isNullOrBlank(serialNumber)) {
            crmHistoryModel.setSerialNumber(Integer.parseInt(serialNumber));
        }
        if (!StringUtils.isNullOrBlank(surveyResult)) {
            crmHistoryModel.setSurveyResult(getSurveyResultState(surveyResult));
        }
        if (!StringUtils.isNullOrBlank(updateAccount)) {
            crmHistoryModel.setUpdateAccount(updateAccount);
        }
        crmHistoryModel.setConnectDate(new java.sql.Date(new Date().getTime()));
        crmHistoryModel.setConnectTime(new Timestamp(new Date().getTime()));
        crmHistoryModel.setUpdateTime(new Timestamp(new Date().getTime()));
        //校验 是否 在crm_history表中插入一条数据
        // 当 id 为空 时，将在crm_history表中插入一条数据
        if (StringUtils.isNullOrBlank(String.valueOf(crmHistoryModel.getId()))) {
            // 当 stage（调研状态） 或 custId（顾客编号） 为 空 时， 不进行数据插入操作
            if (StringUtils.isNullOrBlank(crmHistoryModel.getStage()) || StringUtils.isNullOrBlank(crmHistoryModel.getCustId())) {
                return null;
            }
            List<CrmHistoryModel> list = null;
            // 校验crnm_history表中是否已经存在 该 调研数据
            // stage = 01 或 stage = 04 时，用 stage、custId、seriaNumber 这三个字段 可以确定 调研信息 的 唯一性（历史数据不作考虑）
            // stage = 02 或 stage = 03 时，用 stage、custId 这两个字段 可以确定 调研信息 的 唯一性（历史数据不作考虑）
            if ("01".equals(crmHistoryModel.getStage()) || "04".equals(crmHistoryModel.getStage())) {
                // stage = 01 或 stage = 04 时，seriaNumber 必须有值，不然 不进行数据插入操作
                if (StringUtils.isNullOrBlank(crmHistoryModel.getSerialNumber())) {
                    return null;
                }
                list = crmHistoryRepository.queryModelByStageAndCustIdAndSerialNumber(crmHistoryModel.getStage(), crmHistoryModel.getCustId(), crmHistoryModel.getSerialNumber());
            } else {
                list = crmHistoryRepository.queryModelByStageAndCustId(crmHistoryModel.getStage(), crmHistoryModel.getCustId());
            }
            // 当 list 有值（即通过查询条件查出库中已存在调研数据，将不进行 数据插入操作）
            if (list != null && !list.isEmpty()) {
                return null;
            }
        }
        crmHistoryModel = crmHistoryRepository.save(crmHistoryModel);
        return crmHistoryModel;
    }

    /**
     * 保存 调研记录日志
     * @param historyId
     * @param surveyResult
     * @param nextConnectDate
     * @param remark
     * @param updateAccount
     * @return
     */
    private CrmHistoryLogModel saveCrmHistoryLog (CrmHistoryLogModel crmHistoryLogModel, String historyId, String surveyResult,
                                                  String nextConnectDate, String remark, String updateAccount) {
        if (crmHistoryLogModel == null) {
            crmHistoryLogModel = new CrmHistoryLogModel();
        }
        if (!StringUtils.isNullOrBlank(historyId)) {
            crmHistoryLogModel.setHistoryId(Integer.parseInt(historyId));
        }
        if (!StringUtils.isNullOrBlank(surveyResult)) {
            crmHistoryLogModel.setSurveyResult(getSurveyResultState(surveyResult));
        }
        if (!StringUtils.isNullOrBlank(nextConnectDate)) {
            Timestamp time = new Timestamp(DateFormatUtils.getFormatDate(nextConnectDate, "yyyy-MM-dd HH:mm:ss").getTime());
            crmHistoryLogModel.setNextConnectDate(time);
        }
        if (!StringUtils.isNullOrBlank(remark)) {
            crmHistoryLogModel.setRemark(remark);
        }
        crmHistoryLogModel.setUpdateAccount(updateAccount);
        crmHistoryLogModel.setUpdateTime(new Timestamp(new Date().getTime()));
        crmHistoryLogModel = crmHistoryLogRepository.save(crmHistoryLogModel);
        return crmHistoryLogModel;
    }

    /**
     * 调研结果 转换
     * @param surveyResult
     * @return
     */
    private String getSurveyResultState(String surveyResult) {
        String surveyResultNum = null;
        for (int i = 1; i <= surveyResultType.length; i++) {
            if (surveyResultType[i - 1].equals(surveyResult)) {
                surveyResultNum = String.valueOf(i);
            }
        }
        return surveyResultNum;
    }
}
